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 "fe-secure-common.h"
32 #include "libpq-int.h"
37 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #ifdef HAVE_NETINET_TCP_H
42 #include <netinet/tcp.h>
44 #include <arpa/inet.h>
49 #ifdef ENABLE_THREAD_SAFETY
51 #include "pthread-win32.h"
57 #include <openssl/ssl.h>
58 #include <openssl/conf.h>
60 #include <openssl/engine.h>
62 #include <openssl/x509v3.h>
64 static int verify_cb(int ok, X509_STORE_CTX *ctx);
65 static int openssl_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 pgtls_init_library(bool do_ssl, int do_crypto)
104 #ifdef ENABLE_THREAD_SAFETY
107 * Disallow changing the flags while we have open connections, else we'd
108 * get completely confused.
110 if (ssl_open_connections != 0)
114 pq_init_ssl_lib = do_ssl;
115 pq_init_crypto_lib = do_crypto;
118 PostgresPollingStatusType
119 pgtls_open_client(PGconn *conn)
121 /* First time through? */
122 if (conn->ssl == NULL)
125 * Create a connection-specific SSL object, and load client
126 * certificate, private key, and trusted CA certs.
128 if (initialize_SSL(conn) != 0)
130 /* initialize_SSL already put a message in conn->errorMessage */
132 return PGRES_POLLING_FAILED;
136 /* Begin or continue the actual handshake */
137 return open_client_SSL(conn);
141 pgtls_read(PGconn *conn, void *ptr, size_t len)
144 int result_errno = 0;
152 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
153 * queue. In general, the current thread's error queue must be empty
154 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
155 * not work reliably. Since the possibility exists that other OpenSSL
156 * clients running in the same thread but not under our control will fail
157 * to call ERR_get_error() themselves (after their own I/O operations),
158 * pro-actively clear the per-thread error queue now.
162 n = SSL_read(conn->ssl, ptr, len);
163 err = SSL_get_error(conn->ssl, n);
166 * Other clients of OpenSSL may fail to call ERR_get_error(), but we
167 * always do, so as to not cause problems for OpenSSL clients that don't
168 * call ERR_clear_error() defensively. Be sure that this happens by
169 * calling now. SSL_get_error() relies on the OpenSSL per-thread error
170 * queue being intact, so this is the earliest possible point
171 * ERR_get_error() may be called.
173 ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
179 /* Not supposed to happen, so we don't translate the msg */
180 printfPQExpBuffer(&conn->errorMessage,
181 "SSL_read failed but did not provide error information\n");
182 /* assume the connection is broken */
183 result_errno = ECONNRESET;
186 case SSL_ERROR_WANT_READ:
189 case SSL_ERROR_WANT_WRITE:
192 * Returning 0 here would cause caller to wait for read-ready,
193 * which is not correct since what SSL wants is wait for
194 * write-ready. The former could get us stuck in an infinite
195 * wait, so don't risk it; busy-loop instead.
198 case SSL_ERROR_SYSCALL:
201 result_errno = SOCK_ERRNO;
202 if (result_errno == EPIPE ||
203 result_errno == ECONNRESET)
204 printfPQExpBuffer(&conn->errorMessage,
206 "server closed the connection unexpectedly\n"
207 "\tThis probably means the server terminated abnormally\n"
208 "\tbefore or while processing the request.\n"));
210 printfPQExpBuffer(&conn->errorMessage,
211 libpq_gettext("SSL SYSCALL error: %s\n"),
212 SOCK_STRERROR(result_errno,
213 sebuf, sizeof(sebuf)));
217 printfPQExpBuffer(&conn->errorMessage,
218 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
219 /* assume the connection is broken */
220 result_errno = ECONNRESET;
226 char *errm = SSLerrmessage(ecode);
228 printfPQExpBuffer(&conn->errorMessage,
229 libpq_gettext("SSL error: %s\n"), errm);
231 /* assume the connection is broken */
232 result_errno = ECONNRESET;
236 case SSL_ERROR_ZERO_RETURN:
239 * Per OpenSSL documentation, this error code is only returned for
240 * a clean connection closure, so we should not report it as a
243 printfPQExpBuffer(&conn->errorMessage,
244 libpq_gettext("SSL connection has been closed unexpectedly\n"));
245 result_errno = ECONNRESET;
249 printfPQExpBuffer(&conn->errorMessage,
250 libpq_gettext("unrecognized SSL error code: %d\n"),
252 /* assume the connection is broken */
253 result_errno = ECONNRESET;
258 /* ensure we return the intended errno to caller */
259 SOCK_ERRNO_SET(result_errno);
265 pgtls_read_pending(PGconn *conn)
267 return SSL_pending(conn->ssl);
271 pgtls_write(PGconn *conn, const void *ptr, size_t len)
274 int result_errno = 0;
281 n = SSL_write(conn->ssl, ptr, len);
282 err = SSL_get_error(conn->ssl, n);
283 ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
289 /* Not supposed to happen, so we don't translate the msg */
290 printfPQExpBuffer(&conn->errorMessage,
291 "SSL_write failed but did not provide error information\n");
292 /* assume the connection is broken */
293 result_errno = ECONNRESET;
296 case SSL_ERROR_WANT_READ:
299 * Returning 0 here causes caller to wait for write-ready, which
300 * is not really the right thing, but it's the best we can do.
304 case SSL_ERROR_WANT_WRITE:
307 case SSL_ERROR_SYSCALL:
310 result_errno = SOCK_ERRNO;
311 if (result_errno == EPIPE || result_errno == ECONNRESET)
312 printfPQExpBuffer(&conn->errorMessage,
314 "server closed the connection unexpectedly\n"
315 "\tThis probably means the server terminated abnormally\n"
316 "\tbefore or while processing the request.\n"));
318 printfPQExpBuffer(&conn->errorMessage,
319 libpq_gettext("SSL SYSCALL error: %s\n"),
320 SOCK_STRERROR(result_errno,
321 sebuf, sizeof(sebuf)));
325 printfPQExpBuffer(&conn->errorMessage,
326 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
327 /* assume the connection is broken */
328 result_errno = ECONNRESET;
334 char *errm = SSLerrmessage(ecode);
336 printfPQExpBuffer(&conn->errorMessage,
337 libpq_gettext("SSL error: %s\n"), errm);
339 /* assume the connection is broken */
340 result_errno = ECONNRESET;
344 case SSL_ERROR_ZERO_RETURN:
347 * Per OpenSSL documentation, this error code is only returned for
348 * a clean connection closure, so we should not report it as a
351 printfPQExpBuffer(&conn->errorMessage,
352 libpq_gettext("SSL connection has been closed unexpectedly\n"));
353 result_errno = ECONNRESET;
357 printfPQExpBuffer(&conn->errorMessage,
358 libpq_gettext("unrecognized SSL error code: %d\n"),
360 /* assume the connection is broken */
361 result_errno = ECONNRESET;
366 /* ensure we return the intended errno to caller */
367 SOCK_ERRNO_SET(result_errno);
373 pgtls_get_finished(PGconn *conn, size_t *len)
379 * OpenSSL does not offer an API to get directly the length of the TLS
380 * Finished message sent, so first do a dummy call to grab this
381 * information and then do an allocation with the correct size.
383 *len = SSL_get_finished(conn->ssl, dummy, sizeof(dummy));
384 result = malloc(*len);
387 (void) SSL_get_finished(conn->ssl, result, *len);
393 pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
395 #ifdef HAVE_X509_GET_SIGNATURE_NID
397 const EVP_MD *algo_type;
398 unsigned char hash[EVP_MAX_MD_SIZE]; /* size for SHA-512 */
399 unsigned int hash_size;
408 peer_cert = conn->peer;
411 * Get the signature algorithm of the certificate to determine the hash
412 * algorithm to use for the result.
414 if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert),
417 printfPQExpBuffer(&conn->errorMessage,
418 libpq_gettext("could not determine server certificate signature algorithm\n"));
423 * The TLS server's certificate bytes need to be hashed with SHA-256 if
424 * its signature algorithm is MD5 or SHA-1 as per RFC 5929
425 * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
426 * is used, the same hash as the signature algorithm is used.
432 algo_type = EVP_sha256();
435 algo_type = EVP_get_digestbynid(algo_nid);
436 if (algo_type == NULL)
438 printfPQExpBuffer(&conn->errorMessage,
439 libpq_gettext("could not find digest for NID %s\n"),
440 OBJ_nid2sn(algo_nid));
446 if (!X509_digest(peer_cert, algo_type, hash, &hash_size))
448 printfPQExpBuffer(&conn->errorMessage,
449 libpq_gettext("could not generate peer certificate hash\n"));
454 cert_hash = malloc(hash_size);
455 if (cert_hash == NULL)
457 printfPQExpBuffer(&conn->errorMessage,
458 libpq_gettext("out of memory\n"));
461 memcpy(cert_hash, hash, hash_size);
466 printfPQExpBuffer(&conn->errorMessage,
467 libpq_gettext("channel binding type \"tls-server-end-point\" is not supported by this build\n"));
472 /* ------------------------------------------------------------ */
473 /* OpenSSL specific code */
474 /* ------------------------------------------------------------ */
477 * Certificate verification callback
479 * This callback allows us to log intermediate problems during
480 * verification, but there doesn't seem to be a clean way to get
481 * our PGconn * structure. So we can't log anything!
483 * This callback also allows us to override the default acceptance
484 * criteria (e.g., accepting self-signed or expired certs), but
485 * for now we accept the default checks.
488 verify_cb(int ok, X509_STORE_CTX *ctx)
495 * OpenSSL-specific wrapper around
496 * pq_verify_peer_name_matches_certificate_name(), converting the ASN1_STRING
497 * into a plain C string.
500 openssl_verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry,
504 const unsigned char *namedata;
506 /* Should not happen... */
507 if (name_entry == NULL)
509 printfPQExpBuffer(&conn->errorMessage,
510 libpq_gettext("SSL certificate's name entry is missing\n"));
515 * GEN_DNS can be only IA5String, equivalent to US ASCII.
517 #ifdef HAVE_ASN1_STRING_GET0_DATA
518 namedata = ASN1_STRING_get0_data(name_entry);
520 namedata = ASN1_STRING_data(name_entry);
522 len = ASN1_STRING_length(name_entry);
524 /* OK to cast from unsigned to plain char, since it's all ASCII. */
525 return pq_verify_peer_name_matches_certificate_name(conn, (const char *) namedata, len, store_name);
529 * Verify that the server certificate matches the hostname we connected to.
531 * The certificate's Common Name and Subject Alternative Names are considered.
534 pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn,
538 STACK_OF(GENERAL_NAME) *peer_san;
543 * First, get the Subject Alternative Names (SANs) from the certificate,
544 * and compare them against the originally given hostname.
546 peer_san = (STACK_OF(GENERAL_NAME) *)
547 X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
551 int san_len = sk_GENERAL_NAME_num(peer_san);
553 for (i = 0; i < san_len; i++)
555 const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
557 if (name->type == GEN_DNS)
562 rc = openssl_verify_peer_name_matches_certificate_name(conn,
569 *first_name = alt_name;
577 sk_GENERAL_NAME_free(peer_san);
581 * If there is no subjectAltName extension of type dNSName, check the
584 * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
585 * dNSName is present, the CN must be ignored.)
587 if (*names_examined == 0)
589 X509_NAME *subject_name;
591 subject_name = X509_get_subject_name(conn->peer);
592 if (subject_name != NULL)
596 cn_index = X509_NAME_get_index_by_NID(subject_name,
601 rc = openssl_verify_peer_name_matches_certificate_name(
603 X509_NAME_ENTRY_get_data(
604 X509_NAME_get_entry(subject_name, cn_index)),
613 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
615 * Callback functions for OpenSSL internal locking. (OpenSSL 1.1.0
616 * does its own locking, and doesn't need these anymore. The
617 * CRYPTO_lock() function was removed in 1.1.0, when the callbacks
618 * were made obsolete, so we assume that if CRYPTO_lock() exists,
619 * the callbacks are still required.)
623 pq_threadidcallback(void)
626 * This is not standards-compliant. pthread_self() returns pthread_t, and
627 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
628 * it, so we have to do it.
630 return (unsigned long) pthread_self();
633 static pthread_mutex_t *pq_lockarray;
636 pq_lockingcallback(int mode, int n, const char *file, int line)
638 if (mode & CRYPTO_LOCK)
640 if (pthread_mutex_lock(&pq_lockarray[n]))
641 PGTHREAD_ERROR("failed to lock mutex");
645 if (pthread_mutex_unlock(&pq_lockarray[n]))
646 PGTHREAD_ERROR("failed to unlock mutex");
649 #endif /* ENABLE_THREAD_SAFETY && HAVE_CRYPTO_LOCK */
652 * Initialize SSL library.
654 * In threadsafe mode, this includes setting up libcrypto callback functions
655 * to do thread locking.
657 * If the caller has told us (through PQinitOpenSSL) that he's taking care
658 * of libcrypto, we expect that callbacks are already set, and won't try to
662 pgtls_init(PGconn *conn)
664 #ifdef ENABLE_THREAD_SAFETY
666 /* Also see similar code in fe-connect.c, default_threadlock() */
667 if (ssl_config_mutex == NULL)
669 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
670 /* loop, another thread own the lock */ ;
671 if (ssl_config_mutex == NULL)
673 if (pthread_mutex_init(&ssl_config_mutex, NULL))
676 InterlockedExchange(&win32_ssl_create_mutex, 0);
679 if (pthread_mutex_lock(&ssl_config_mutex))
682 #ifdef HAVE_CRYPTO_LOCK
683 if (pq_init_crypto_lib)
686 * If necessary, set up an array to hold locks for libcrypto.
687 * libcrypto will tell us how big to make this array.
689 if (pq_lockarray == NULL)
693 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
696 pthread_mutex_unlock(&ssl_config_mutex);
699 for (i = 0; i < CRYPTO_num_locks(); i++)
701 if (pthread_mutex_init(&pq_lockarray[i], NULL))
705 pthread_mutex_unlock(&ssl_config_mutex);
711 if (ssl_open_connections++ == 0)
714 * These are only required for threaded libcrypto applications,
715 * but make sure we don't stomp on them if they're already set.
717 if (CRYPTO_get_id_callback() == NULL)
718 CRYPTO_set_id_callback(pq_threadidcallback);
719 if (CRYPTO_get_locking_callback() == NULL)
720 CRYPTO_set_locking_callback(pq_lockingcallback);
723 #endif /* HAVE_CRYPTO_LOCK */
724 #endif /* ENABLE_THREAD_SAFETY */
726 if (!ssl_lib_initialized)
730 #ifdef HAVE_OPENSSL_INIT_SSL
731 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
733 OPENSSL_config(NULL);
735 SSL_load_error_strings();
738 ssl_lib_initialized = true;
741 #ifdef ENABLE_THREAD_SAFETY
742 pthread_mutex_unlock(&ssl_config_mutex);
748 * This function is needed because if the libpq library is unloaded
749 * from the application, the callback functions will no longer exist when
750 * libcrypto is used by other parts of the system. For this reason,
751 * we unregister the callback functions when the last libpq
752 * connection is closed. (The same would apply for OpenSSL callbacks
755 * Callbacks are only set when we're compiled in threadsafe mode, so
756 * we only need to remove them in this case. They are also not needed
757 * with OpenSSL 1.1.0 anymore.
760 destroy_ssl_system(void)
762 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
763 /* Mutex is created in initialize_ssl_system() */
764 if (pthread_mutex_lock(&ssl_config_mutex))
767 if (pq_init_crypto_lib && ssl_open_connections > 0)
768 --ssl_open_connections;
770 if (pq_init_crypto_lib && ssl_open_connections == 0)
773 * No connections left, unregister libcrypto callbacks, if no one
774 * registered different ones in the meantime.
776 if (CRYPTO_get_locking_callback() == pq_lockingcallback)
777 CRYPTO_set_locking_callback(NULL);
778 if (CRYPTO_get_id_callback() == pq_threadidcallback)
779 CRYPTO_set_id_callback(NULL);
782 * We don't free the lock array. If we get another connection in this
783 * process, we will just re-use them with the existing mutexes.
785 * This means we leak a little memory on repeated load/unload of the
790 pthread_mutex_unlock(&ssl_config_mutex);
795 * Create per-connection SSL object, and load the client certificate,
796 * private key, and trusted CA certs.
798 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
801 initialize_SSL(PGconn *conn)
803 SSL_CTX *SSL_context;
805 char homedir[MAXPGPATH];
806 char fnbuf[MAXPGPATH];
811 EVP_PKEY *pkey = NULL;
814 * We'll need the home directory if any of the relevant parameters are
815 * defaulted. If pqGetHomeDirectory fails, act as though none of the
816 * files could be found.
818 if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
819 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
820 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
821 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
822 have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
823 else /* won't need it */
824 have_homedir = false;
827 * Create a new SSL_CTX object.
829 * We used to share a single SSL_CTX between all connections, but it was
830 * complicated if connections used different certificates. So now we
831 * create a separate context for each connection, and accept the overhead.
833 SSL_context = SSL_CTX_new(SSLv23_method());
836 char *err = SSLerrmessage(ERR_get_error());
838 printfPQExpBuffer(&conn->errorMessage,
839 libpq_gettext("could not create SSL context: %s\n"),
845 /* Disable old protocol versions */
846 SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
849 * Disable OpenSSL's moving-write-buffer sanity check, because it causes
850 * unnecessary failures in nonblocking send cases.
852 SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
855 * If the root cert file exists, load it so we can perform certificate
856 * verification. If sslmode is "verify-full" we will also do further
857 * verification after the connection has been completed.
859 if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
860 strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
861 else if (have_homedir)
862 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
866 if (fnbuf[0] != '\0' &&
867 stat(fnbuf, &buf) == 0)
871 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
873 char *err = SSLerrmessage(ERR_get_error());
875 printfPQExpBuffer(&conn->errorMessage,
876 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
879 SSL_CTX_free(SSL_context);
883 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
885 if (conn->sslcrl && strlen(conn->sslcrl) > 0)
886 strlcpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
887 else if (have_homedir)
888 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
892 /* Set the flags to check against the complete CRL chain */
893 if (fnbuf[0] != '\0' &&
894 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
896 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
897 #ifdef X509_V_FLAG_CRL_CHECK
898 X509_STORE_set_flags(cvstore,
899 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
901 char *err = SSLerrmessage(ERR_get_error());
903 printfPQExpBuffer(&conn->errorMessage,
904 libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
907 SSL_CTX_free(SSL_context);
911 /* if not found, silently ignore; we do not require CRL */
914 have_rootcert = true;
919 * stat() failed; assume root file doesn't exist. If sslmode is
920 * verify-ca or verify-full, this is an error. Otherwise, continue
921 * without performing any server cert verification.
923 if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
926 * The only way to reach here with an empty filename is if
927 * pqGetHomeDirectory failed. That's a sufficiently unusual case
928 * that it seems worth having a specialized error message for it.
930 if (fnbuf[0] == '\0')
931 printfPQExpBuffer(&conn->errorMessage,
932 libpq_gettext("could not get home directory to locate root certificate file\n"
933 "Either provide the file or change sslmode to disable server certificate verification.\n"));
935 printfPQExpBuffer(&conn->errorMessage,
936 libpq_gettext("root certificate file \"%s\" does not exist\n"
937 "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
938 SSL_CTX_free(SSL_context);
941 have_rootcert = false;
944 /* Read the client certificate file */
945 if (conn->sslcert && strlen(conn->sslcert) > 0)
946 strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
947 else if (have_homedir)
948 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
952 if (fnbuf[0] == '\0')
954 /* no home directory, proceed without a client cert */
957 else if (stat(fnbuf, &buf) != 0)
960 * If file is not present, just go on without a client cert; server
961 * might or might not accept the connection. Any other error,
962 * however, is grounds for complaint.
964 if (errno != ENOENT && errno != ENOTDIR)
966 printfPQExpBuffer(&conn->errorMessage,
967 libpq_gettext("could not open certificate file \"%s\": %s\n"),
968 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
969 SSL_CTX_free(SSL_context);
977 * Cert file exists, so load it. Since OpenSSL doesn't provide the
978 * equivalent of "SSL_use_certificate_chain_file", we have to load it
979 * into the SSL context, rather than the SSL object.
981 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
983 char *err = SSLerrmessage(ERR_get_error());
985 printfPQExpBuffer(&conn->errorMessage,
986 libpq_gettext("could not read certificate file \"%s\": %s\n"),
989 SSL_CTX_free(SSL_context);
993 /* need to load the associated private key, too */
998 * The SSL context is now loaded with the correct root and client
999 * certificates. Create a connection-specific SSL object. The private key
1000 * is loaded directly into the SSL object. (We could load the private key
1001 * into the context, too, but we have done it this way historically, and
1002 * it doesn't really matter.)
1004 if (!(conn->ssl = SSL_new(SSL_context)) ||
1005 !SSL_set_app_data(conn->ssl, conn) ||
1006 !my_SSL_set_fd(conn, conn->sock))
1008 char *err = SSLerrmessage(ERR_get_error());
1010 printfPQExpBuffer(&conn->errorMessage,
1011 libpq_gettext("could not establish SSL connection: %s\n"),
1014 SSL_CTX_free(SSL_context);
1017 conn->ssl_in_use = true;
1020 * SSL contexts are reference counted by OpenSSL. We can free it as soon
1021 * as we have created the SSL object, and it will stick around for as long
1022 * as it's actually needed.
1024 SSL_CTX_free(SSL_context);
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(ERR_get_error());
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(ERR_get_error());
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(ERR_get_error());
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(ERR_get_error());
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 strlcpy(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(ERR_get_error());
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(ERR_get_error());
1176 printfPQExpBuffer(&conn->errorMessage,
1177 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1184 * If a root cert was loaded, also set our certificate verification
1188 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1191 * Set compression option if the OpenSSL version used supports it (from
1194 #ifdef SSL_OP_NO_COMPRESSION
1195 if (conn->sslcompression && conn->sslcompression[0] == '0')
1196 SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1198 SSL_clear_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1205 * Attempt to negotiate SSL connection.
1207 static PostgresPollingStatusType
1208 open_client_SSL(PGconn *conn)
1213 r = SSL_connect(conn->ssl);
1216 int err = SSL_get_error(conn->ssl, r);
1217 unsigned long ecode;
1219 ecode = ERR_get_error();
1222 case SSL_ERROR_WANT_READ:
1223 return PGRES_POLLING_READING;
1225 case SSL_ERROR_WANT_WRITE:
1226 return PGRES_POLLING_WRITING;
1228 case SSL_ERROR_SYSCALL:
1233 printfPQExpBuffer(&conn->errorMessage,
1234 libpq_gettext("SSL SYSCALL error: %s\n"),
1235 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1237 printfPQExpBuffer(&conn->errorMessage,
1238 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1240 return PGRES_POLLING_FAILED;
1244 char *err = SSLerrmessage(ecode);
1246 printfPQExpBuffer(&conn->errorMessage,
1247 libpq_gettext("SSL error: %s\n"),
1251 return PGRES_POLLING_FAILED;
1255 printfPQExpBuffer(&conn->errorMessage,
1256 libpq_gettext("unrecognized SSL error code: %d\n"),
1259 return PGRES_POLLING_FAILED;
1264 * We already checked the server certificate in initialize_SSL() using
1265 * SSL_CTX_set_verify(), if root.crt exists.
1268 /* get server certificate */
1269 conn->peer = SSL_get_peer_certificate(conn->ssl);
1270 if (conn->peer == NULL)
1274 err = SSLerrmessage(ERR_get_error());
1276 printfPQExpBuffer(&conn->errorMessage,
1277 libpq_gettext("certificate could not be obtained: %s\n"),
1281 return PGRES_POLLING_FAILED;
1284 if (!pq_verify_peer_name_matches_certificate(conn))
1287 return PGRES_POLLING_FAILED;
1290 /* SSL handshake is complete */
1291 return PGRES_POLLING_OK;
1295 pgtls_close(PGconn *conn)
1297 bool destroy_needed = false;
1302 * We can't destroy everything SSL-related here due to the possible
1303 * later calls to OpenSSL routines which may need our thread
1304 * callbacks, so set a flag here and check at the end.
1306 destroy_needed = true;
1308 SSL_shutdown(conn->ssl);
1309 SSL_free(conn->ssl);
1311 conn->ssl_in_use = false;
1316 X509_free(conn->peer);
1320 #ifdef USE_SSL_ENGINE
1323 ENGINE_finish(conn->engine);
1324 ENGINE_free(conn->engine);
1325 conn->engine = NULL;
1330 * This will remove our SSL locking hooks, if this is the last SSL
1331 * connection, which means we must wait to call it until after all SSL
1332 * calls have been made, otherwise we can end up with a race condition and
1333 * possible deadlocks.
1335 * See comments above destroy_ssl_system().
1338 destroy_ssl_system();
1343 * Obtain reason string for passed SSL errcode
1345 * ERR_get_error() is used by caller to get errcode to pass here.
1347 * Some caution is needed here since ERR_reason_error_string will
1348 * return NULL if it doesn't recognize the error code. We don't
1349 * want to return NULL ever.
1351 static char ssl_nomem[] = "out of memory allocating error description";
1353 #define SSL_ERR_LEN 128
1356 SSLerrmessage(unsigned long ecode)
1358 const char *errreason;
1361 errbuf = malloc(SSL_ERR_LEN);
1366 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1369 errreason = ERR_reason_error_string(ecode);
1370 if (errreason != NULL)
1372 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1375 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1380 SSLerrfree(char *buf)
1382 if (buf != ssl_nomem)
1386 /* ------------------------------------------------------------ */
1387 /* SSL information functions */
1388 /* ------------------------------------------------------------ */
1391 * Return pointer to OpenSSL object.
1394 PQgetssl(PGconn *conn)
1402 PQsslStruct(PGconn *conn, const char *struct_name)
1406 if (strcmp(struct_name, "OpenSSL") == 0)
1412 PQsslAttributeNames(PGconn *conn)
1414 static const char *const result[] = {
1427 PQsslAttribute(PGconn *conn, const char *attribute_name)
1431 if (conn->ssl == NULL)
1434 if (strcmp(attribute_name, "library") == 0)
1437 if (strcmp(attribute_name, "key_bits") == 0)
1439 static char sslbits_str[12];
1442 SSL_get_cipher_bits(conn->ssl, &sslbits);
1443 snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1447 if (strcmp(attribute_name, "cipher") == 0)
1448 return SSL_get_cipher(conn->ssl);
1450 if (strcmp(attribute_name, "compression") == 0)
1451 return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1453 if (strcmp(attribute_name, "protocol") == 0)
1454 return SSL_get_version(conn->ssl);
1456 return NULL; /* unknown attribute */
1460 * Private substitute BIO: this does the sending and receiving using
1461 * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1462 * functions to disable SIGPIPE and give better error messages on I/O errors.
1464 * These functions are closely modelled on the standard socket BIO in OpenSSL;
1465 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1466 * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1467 * to retry; do we need to adopt their logic for that?
1470 #ifndef HAVE_BIO_GET_DATA
1471 #define BIO_get_data(bio) (bio->ptr)
1472 #define BIO_set_data(bio, data) (bio->ptr = data)
1475 static BIO_METHOD *my_bio_methods;
1478 my_sock_read(BIO *h, char *buf, int size)
1482 res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1483 BIO_clear_retry_flags(h);
1486 /* If we were interrupted, tell caller to retry */
1492 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1496 BIO_set_retry_read(h);
1508 my_sock_write(BIO *h, const char *buf, int size)
1512 res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1513 BIO_clear_retry_flags(h);
1516 /* If we were interrupted, tell caller to retry */
1522 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1526 BIO_set_retry_write(h);
1538 my_BIO_s_socket(void)
1540 if (!my_bio_methods)
1542 BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1543 #ifdef HAVE_BIO_METH_NEW
1546 my_bio_index = BIO_get_new_index();
1547 if (my_bio_index == -1)
1549 my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1550 if (!my_bio_methods)
1554 * As of this writing, these functions never fail. But check anyway,
1555 * like OpenSSL's own examples do.
1557 if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1558 !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1559 !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1560 !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1561 !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1562 !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1563 !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1564 !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1566 BIO_meth_free(my_bio_methods);
1567 my_bio_methods = NULL;
1571 my_bio_methods = malloc(sizeof(BIO_METHOD));
1572 if (!my_bio_methods)
1574 memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1575 my_bio_methods->bread = my_sock_read;
1576 my_bio_methods->bwrite = my_sock_write;
1579 return my_bio_methods;
1582 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
1584 my_SSL_set_fd(PGconn *conn, int fd)
1588 BIO_METHOD *bio_method;
1590 bio_method = my_BIO_s_socket();
1591 if (bio_method == NULL)
1593 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1596 bio = BIO_new(bio_method);
1599 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1602 BIO_set_data(bio, conn);
1604 SSL_set_bio(conn->ssl, bio, bio);
1605 BIO_set_fd(bio, fd, BIO_NOCLOSE);