1 /*-------------------------------------------------------------------------
4 * functions related to setting up a secure connection to the backend.
5 * Secure connections are expected to provide confidentiality,
6 * message integrity and endpoint authentication.
9 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
10 * Portions Copyright (c) 1994, Regents of the University of California
14 * $PostgreSQL: pgsql/src/interfaces/libpq/fe-secure.c,v 1.136 2010/07/14 17:09:45 tgl Exp $
18 * We don't provide informational callbacks here (like
19 * info_cb() in be-secure.c), since there's no good mechanism to
20 * display such information to the user.
22 *-------------------------------------------------------------------------
25 #include "postgres_fe.h"
34 #include "libpq-int.h"
39 #include <sys/socket.h>
42 #include <netinet/in.h>
43 #ifdef HAVE_NETINET_TCP_H
44 #include <netinet/tcp.h>
46 #include <arpa/inet.h>
51 #ifdef ENABLE_THREAD_SAFETY
53 #include "pthread-win32.h"
61 #include <openssl/ssl.h>
62 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L)
63 #include <openssl/conf.h>
66 #include <openssl/engine.h>
71 #define USER_CERT_FILE ".postgresql/postgresql.crt"
72 #define USER_KEY_FILE ".postgresql/postgresql.key"
73 #define ROOT_CERT_FILE ".postgresql/root.crt"
74 #define ROOT_CRL_FILE ".postgresql/root.crl"
76 /* On Windows, the "home" directory is already PostgreSQL-specific */
77 #define USER_CERT_FILE "postgresql.crt"
78 #define USER_KEY_FILE "postgresql.key"
79 #define ROOT_CERT_FILE "root.crt"
80 #define ROOT_CRL_FILE "root.crl"
83 static bool verify_peer_name_matches_certificate(PGconn *);
84 static int verify_cb(int ok, X509_STORE_CTX *ctx);
85 static int init_ssl_system(PGconn *conn);
86 static void destroy_ssl_system(void);
87 static int initialize_SSL(PGconn *conn);
88 static void destroySSL(void);
89 static PostgresPollingStatusType open_client_SSL(PGconn *);
90 static void close_SSL(PGconn *);
91 static char *SSLerrmessage(void);
92 static void SSLerrfree(char *buf);
94 static bool pq_init_ssl_lib = true;
95 static bool pq_init_crypto_lib = true;
96 static SSL_CTX *SSL_context = NULL;
98 #ifdef ENABLE_THREAD_SAFETY
99 static long ssl_open_connections = 0;
102 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
104 static pthread_mutex_t ssl_config_mutex = NULL;
105 static long win32_ssl_create_mutex = 0;
107 #endif /* ENABLE_THREAD_SAFETY */
112 * Macros to handle disabling and then restoring the state of SIGPIPE handling.
113 * On Windows, these are all no-ops since there's no SIGPIPEs.
118 #define SIGPIPE_MASKED(conn) ((conn)->sigpipe_so || (conn)->sigpipe_flag)
120 #ifdef ENABLE_THREAD_SAFETY
125 bool sigpipe_pending;
129 #define DECLARE_SIGPIPE_INFO(spinfo) struct sigpipe_info spinfo
131 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
133 (spinfo).got_epipe = false; \
134 if (!SIGPIPE_MASKED(conn)) \
136 if (pq_block_sigpipe(&(spinfo).oldsigmask, \
137 &(spinfo).sigpipe_pending) < 0) \
142 #define REMEMBER_EPIPE(spinfo, cond) \
145 (spinfo).got_epipe = true; \
148 #define RESTORE_SIGPIPE(conn, spinfo) \
150 if (!SIGPIPE_MASKED(conn)) \
151 pq_reset_sigpipe(&(spinfo).oldsigmask, (spinfo).sigpipe_pending, \
152 (spinfo).got_epipe); \
154 #else /* !ENABLE_THREAD_SAFETY */
156 #define DECLARE_SIGPIPE_INFO(spinfo) pqsigfunc spinfo = NULL
158 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
160 if (!SIGPIPE_MASKED(conn)) \
161 spinfo = pqsignal(SIGPIPE, SIG_IGN); \
164 #define REMEMBER_EPIPE(spinfo, cond)
166 #define RESTORE_SIGPIPE(conn, spinfo) \
168 if (!SIGPIPE_MASKED(conn)) \
169 pqsignal(SIGPIPE, spinfo); \
171 #endif /* ENABLE_THREAD_SAFETY */
174 #define DECLARE_SIGPIPE_INFO(spinfo)
175 #define DISABLE_SIGPIPE(conn, spinfo, failaction)
176 #define REMEMBER_EPIPE(spinfo, cond)
177 #define RESTORE_SIGPIPE(conn, spinfo)
180 /* ------------------------------------------------------------ */
181 /* Procedures common to all secure sessions */
182 /* ------------------------------------------------------------ */
186 * Exported function to allow application to tell us it's already
187 * initialized OpenSSL.
190 PQinitSSL(int do_init)
192 PQinitOpenSSL(do_init, do_init);
196 * Exported function to allow application to tell us it's already
197 * initialized OpenSSL and/or libcrypto.
200 PQinitOpenSSL(int do_ssl, int do_crypto)
203 #ifdef ENABLE_THREAD_SAFETY
206 * Disallow changing the flags while we have open connections, else we'd
207 * get completely confused.
209 if (ssl_open_connections != 0)
213 pq_init_ssl_lib = do_ssl;
214 pq_init_crypto_lib = do_crypto;
219 * Initialize global SSL context
222 pqsecure_initialize(PGconn *conn)
227 r = init_ssl_system(conn);
234 * Destroy global context
237 pqsecure_destroy(void)
245 * Begin or continue negotiating a secure session.
247 PostgresPollingStatusType
248 pqsecure_open_client(PGconn *conn)
251 /* First time through? */
252 if (conn->ssl == NULL)
254 /* We cannot use MSG_NOSIGNAL to block SIGPIPE when using SSL */
255 conn->sigpipe_flag = false;
257 /* Create a connection-specific SSL object */
258 if (!(conn->ssl = SSL_new(SSL_context)) ||
259 !SSL_set_app_data(conn->ssl, conn) ||
260 !SSL_set_fd(conn->ssl, conn->sock))
262 char *err = SSLerrmessage();
264 printfPQExpBuffer(&conn->errorMessage,
265 libpq_gettext("could not establish SSL connection: %s\n"),
269 return PGRES_POLLING_FAILED;
273 * Load client certificate, private key, and trusted CA certs.
275 if (initialize_SSL(conn) != 0)
277 /* initialize_SSL already put a message in conn->errorMessage */
279 return PGRES_POLLING_FAILED;
283 /* Begin or continue the actual handshake */
284 return open_client_SSL(conn);
286 /* shouldn't get here */
287 return PGRES_POLLING_FAILED;
292 * Close secure session.
295 pqsecure_close(PGconn *conn)
304 * Read data from a secure connection.
307 pqsecure_read(PGconn *conn, void *ptr, size_t len)
316 DECLARE_SIGPIPE_INFO(spinfo);
318 /* SSL_read can write to the socket, so we need to disable SIGPIPE */
319 DISABLE_SIGPIPE(conn, spinfo, return -1);
323 n = SSL_read(conn->ssl, ptr, len);
324 err = SSL_get_error(conn->ssl, n);
329 case SSL_ERROR_WANT_READ:
332 case SSL_ERROR_WANT_WRITE:
335 * Returning 0 here would cause caller to wait for read-ready,
336 * which is not correct since what SSL wants is wait for
337 * write-ready. The former could get us stuck in an infinite
338 * wait, so don't risk it; busy-loop instead.
341 case SSL_ERROR_SYSCALL:
347 REMEMBER_EPIPE(spinfo, SOCK_ERRNO == EPIPE);
348 printfPQExpBuffer(&conn->errorMessage,
349 libpq_gettext("SSL SYSCALL error: %s\n"),
350 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
354 printfPQExpBuffer(&conn->errorMessage,
355 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
357 SOCK_ERRNO_SET(ECONNRESET);
364 char *err = SSLerrmessage();
366 printfPQExpBuffer(&conn->errorMessage,
367 libpq_gettext("SSL error: %s\n"), err);
371 case SSL_ERROR_ZERO_RETURN:
372 SOCK_ERRNO_SET(ECONNRESET);
376 printfPQExpBuffer(&conn->errorMessage,
377 libpq_gettext("unrecognized SSL error code: %d\n"),
383 RESTORE_SIGPIPE(conn, spinfo);
387 n = recv(conn->sock, ptr, len, 0);
393 * Write data to a secure connection.
396 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
400 DECLARE_SIGPIPE_INFO(spinfo);
407 DISABLE_SIGPIPE(conn, spinfo, return -1);
410 n = SSL_write(conn->ssl, ptr, len);
411 err = SSL_get_error(conn->ssl, n);
416 case SSL_ERROR_WANT_READ:
419 * Returning 0 here causes caller to wait for write-ready,
420 * which is not really the right thing, but it's the best we
425 case SSL_ERROR_WANT_WRITE:
428 case SSL_ERROR_SYSCALL:
434 REMEMBER_EPIPE(spinfo, SOCK_ERRNO == EPIPE);
435 printfPQExpBuffer(&conn->errorMessage,
436 libpq_gettext("SSL SYSCALL error: %s\n"),
437 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
441 printfPQExpBuffer(&conn->errorMessage,
442 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
443 SOCK_ERRNO_SET(ECONNRESET);
450 char *err = SSLerrmessage();
452 printfPQExpBuffer(&conn->errorMessage,
453 libpq_gettext("SSL error: %s\n"), err);
457 case SSL_ERROR_ZERO_RETURN:
458 SOCK_ERRNO_SET(ECONNRESET);
462 printfPQExpBuffer(&conn->errorMessage,
463 libpq_gettext("unrecognized SSL error code: %d\n"),
475 if (conn->sigpipe_flag)
476 flags |= MSG_NOSIGNAL;
479 #endif /* MSG_NOSIGNAL */
481 DISABLE_SIGPIPE(conn, spinfo, return -1);
483 n = send(conn->sock, ptr, len, flags);
488 * If we see an EINVAL, it may be because MSG_NOSIGNAL isn't
489 * available on this machine. So, clear sigpipe_flag so we don't
490 * try the flag again, and retry the send().
493 if (flags != 0 && SOCK_ERRNO == EINVAL)
495 conn->sigpipe_flag = false;
499 #endif /* MSG_NOSIGNAL */
501 REMEMBER_EPIPE(spinfo, SOCK_ERRNO == EPIPE);
505 RESTORE_SIGPIPE(conn, spinfo);
510 /* ------------------------------------------------------------ */
511 /* SSL specific code */
512 /* ------------------------------------------------------------ */
516 * Certificate verification callback
518 * This callback allows us to log intermediate problems during
519 * verification, but there doesn't seem to be a clean way to get
520 * our PGconn * structure. So we can't log anything!
522 * This callback also allows us to override the default acceptance
523 * criteria (e.g., accepting self-signed or expired certs), but
524 * for now we accept the default checks.
527 verify_cb(int ok, X509_STORE_CTX *ctx)
534 * Check if a wildcard certificate matches the server hostname.
536 * The rule for this is:
537 * 1. We only match the '*' character as wildcard
538 * 2. We match only wildcards at the start of the string
539 * 3. The '*' character does *not* match '.', meaning that we match only
540 * a single pathname component.
541 * 4. We don't support more than one '*' in a single pattern.
543 * This is roughly in line with RFC2818, but contrary to what most browsers
544 * appear to be implementing (point 3 being the difference)
546 * Matching is always case-insensitive, since DNS is case insensitive.
549 wildcard_certificate_match(const char *pattern, const char *string)
551 int lenpat = strlen(pattern);
552 int lenstr = strlen(string);
554 /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
561 /* If pattern is longer than the string, we can never match */
564 if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
567 * If string does not end in pattern (minus the wildcard), we don't
572 if (strchr(string, '.') < string + lenstr - lenpat)
575 * If there is a dot left of where the pattern started to match, we
576 * don't match (rule 3)
580 /* String ended with pattern, and didn't have a dot before, so we match */
586 * Verify that common name resolves to peer.
589 verify_peer_name_matches_certificate(PGconn *conn)
592 * If told not to verify the peer name, don't do it. Return true indicating
593 * that the verification was successful.
595 if (strcmp(conn->sslmode, "verify-full") != 0)
598 if (!(conn->pghost && conn->pghost[0] != '\0'))
600 printfPQExpBuffer(&conn->errorMessage,
601 libpq_gettext("host name must be specified for a verified SSL connection\n"));
607 * Compare CN to originally given hostname.
609 * XXX: Should support alternate names here
611 if (pg_strcasecmp(conn->peer_cn, conn->pghost) == 0)
612 /* Exact name match */
614 else if (wildcard_certificate_match(conn->peer_cn, conn->pghost))
615 /* Matched wildcard certificate */
619 printfPQExpBuffer(&conn->errorMessage,
620 libpq_gettext("server common name \"%s\" does not match host name \"%s\"\n"),
621 conn->peer_cn, conn->pghost);
627 #ifdef ENABLE_THREAD_SAFETY
629 * Callback functions for OpenSSL internal locking
633 pq_threadidcallback(void)
636 * This is not standards-compliant. pthread_self() returns pthread_t, and
637 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
638 * it, so we have to do it.
640 return (unsigned long) pthread_self();
643 static pthread_mutex_t *pq_lockarray;
646 pq_lockingcallback(int mode, int n, const char *file, int line)
648 if (mode & CRYPTO_LOCK)
650 if (pthread_mutex_lock(&pq_lockarray[n]))
651 PGTHREAD_ERROR("failed to lock mutex");
655 if (pthread_mutex_unlock(&pq_lockarray[n]))
656 PGTHREAD_ERROR("failed to unlock mutex");
659 #endif /* ENABLE_THREAD_SAFETY */
662 * Initialize SSL system, in particular creating the SSL_context object
663 * that will be shared by all SSL-using connections in this process.
665 * In threadsafe mode, this includes setting up libcrypto callback functions
666 * to do thread locking.
668 * If the caller has told us (through PQinitOpenSSL) that he's taking care
669 * of libcrypto, we expect that callbacks are already set, and won't try to
672 * The conn parameter is only used to be able to pass back an error
673 * message - no connection-local setup is made here.
675 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
678 init_ssl_system(PGconn *conn)
680 #ifdef ENABLE_THREAD_SAFETY
682 /* Also see similar code in fe-connect.c, default_threadlock() */
683 if (ssl_config_mutex == NULL)
685 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
686 /* loop, another thread own the lock */ ;
687 if (ssl_config_mutex == NULL)
689 if (pthread_mutex_init(&ssl_config_mutex, NULL))
692 InterlockedExchange(&win32_ssl_create_mutex, 0);
695 if (pthread_mutex_lock(&ssl_config_mutex))
698 if (pq_init_crypto_lib)
701 * If necessary, set up an array to hold locks for libcrypto.
702 * libcrypto will tell us how big to make this array.
704 if (pq_lockarray == NULL)
708 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
711 pthread_mutex_unlock(&ssl_config_mutex);
714 for (i = 0; i < CRYPTO_num_locks(); i++)
716 if (pthread_mutex_init(&pq_lockarray[i], NULL))
720 pthread_mutex_unlock(&ssl_config_mutex);
726 if (ssl_open_connections++ == 0)
728 /* These are only required for threaded libcrypto applications */
729 CRYPTO_set_id_callback(pq_threadidcallback);
730 CRYPTO_set_locking_callback(pq_lockingcallback);
733 #endif /* ENABLE_THREAD_SAFETY */
739 #if SSLEAY_VERSION_NUMBER >= 0x00907000L
740 OPENSSL_config(NULL);
743 SSL_load_error_strings();
746 SSL_context = SSL_CTX_new(TLSv1_method());
749 char *err = SSLerrmessage();
751 printfPQExpBuffer(&conn->errorMessage,
752 libpq_gettext("could not create SSL context: %s\n"),
755 #ifdef ENABLE_THREAD_SAFETY
756 pthread_mutex_unlock(&ssl_config_mutex);
762 #ifdef ENABLE_THREAD_SAFETY
763 pthread_mutex_unlock(&ssl_config_mutex);
769 * This function is needed because if the libpq library is unloaded
770 * from the application, the callback functions will no longer exist when
771 * libcrypto is used by other parts of the system. For this reason,
772 * we unregister the callback functions when the last libpq
773 * connection is closed. (The same would apply for OpenSSL callbacks
776 * Callbacks are only set when we're compiled in threadsafe mode, so
777 * we only need to remove them in this case.
780 destroy_ssl_system(void)
782 #ifdef ENABLE_THREAD_SAFETY
783 /* Mutex is created in initialize_ssl_system() */
784 if (pthread_mutex_lock(&ssl_config_mutex))
787 if (pq_init_crypto_lib && ssl_open_connections > 0)
788 --ssl_open_connections;
790 if (pq_init_crypto_lib && ssl_open_connections == 0)
792 /* No connections left, unregister libcrypto callbacks */
793 CRYPTO_set_locking_callback(NULL);
794 CRYPTO_set_id_callback(NULL);
797 * We don't free the lock array. If we get another connection in this
798 * process, we will just re-use it with the existing mutexes.
800 * This means we leak a little memory on repeated load/unload of the
805 pthread_mutex_unlock(&ssl_config_mutex);
810 * Initialize (potentially) per-connection SSL data, namely the
811 * client certificate, private key, and trusted CA certs.
813 * conn->ssl must already be created. It receives the connection's client
814 * certificate and private key. Note however that certificates also get
815 * loaded into the SSL_context object, and are therefore accessible to all
816 * connections in this process. This should be OK as long as there aren't
817 * any hash collisions among the certs.
819 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
822 initialize_SSL(PGconn *conn)
825 char homedir[MAXPGPATH];
826 char fnbuf[MAXPGPATH];
829 EVP_PKEY *pkey = NULL;
832 * We'll need the home directory if any of the relevant parameters are
835 if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
836 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
837 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
838 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
840 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
842 printfPQExpBuffer(&conn->errorMessage,
843 libpq_gettext("could not get home directory to locate client certificate files\n"));
852 /* Read the client certificate file */
853 if (conn->sslcert && strlen(conn->sslcert) > 0)
854 strncpy(fnbuf, conn->sslcert, sizeof(fnbuf));
856 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
858 if (stat(fnbuf, &buf) != 0)
861 * If file is not present, just go on without a client cert; server
862 * might or might not accept the connection. Any other error,
863 * however, is grounds for complaint.
867 printfPQExpBuffer(&conn->errorMessage,
868 libpq_gettext("could not open certificate file \"%s\": %s\n"),
869 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
877 * Cert file exists, so load it. Since OpenSSL doesn't provide the
878 * equivalent of "SSL_use_certificate_chain_file", we actually have to
879 * load the file twice. The first call loads any extra certs after
880 * the first one into chain-cert storage associated with the
881 * SSL_context. The second call loads the first cert (only) into the
882 * SSL object, where it will be correctly paired with the private key
883 * we load below. We do it this way so that each connection
884 * understands which subject cert to present, in case different
885 * sslcert settings are used for different connections in the same
888 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
890 char *err = SSLerrmessage();
892 printfPQExpBuffer(&conn->errorMessage,
893 libpq_gettext("could not read certificate file \"%s\": %s\n"),
898 if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
900 char *err = SSLerrmessage();
902 printfPQExpBuffer(&conn->errorMessage,
903 libpq_gettext("could not read certificate file \"%s\": %s\n"),
908 /* need to load the associated private key, too */
913 * Read the SSL key. If a key is specified, treat it as an engine:key
914 * combination if there is colon present - we don't support files with
915 * colon in the name. The exception is if the second character is a colon,
916 * in which case it can be a Windows filename with drive specification.
918 if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
920 #ifdef USE_SSL_ENGINE
921 if (strchr(conn->sslkey, ':')
923 && conn->sslkey[1] != ':'
927 /* Colon, but not in second character, treat as engine:key */
928 char *engine_str = strdup(conn->sslkey);
929 char *engine_colon = strchr(engine_str, ':');
931 *engine_colon = '\0'; /* engine_str now has engine name */
932 engine_colon++; /* engine_colon now has key name */
934 conn->engine = ENGINE_by_id(engine_str);
935 if (conn->engine == NULL)
937 char *err = SSLerrmessage();
939 printfPQExpBuffer(&conn->errorMessage,
940 libpq_gettext("could not load SSL engine \"%s\": %s\n"),
947 if (ENGINE_init(conn->engine) == 0)
949 char *err = SSLerrmessage();
951 printfPQExpBuffer(&conn->errorMessage,
952 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
955 ENGINE_free(conn->engine);
961 pkey = ENGINE_load_private_key(conn->engine, engine_colon,
965 char *err = SSLerrmessage();
967 printfPQExpBuffer(&conn->errorMessage,
968 libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
969 engine_colon, engine_str, err);
971 ENGINE_finish(conn->engine);
972 ENGINE_free(conn->engine);
977 if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
979 char *err = SSLerrmessage();
981 printfPQExpBuffer(&conn->errorMessage,
982 libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
983 engine_colon, engine_str, err);
985 ENGINE_finish(conn->engine);
986 ENGINE_free(conn->engine);
994 fnbuf[0] = '\0'; /* indicate we're not going to load from a
998 #endif /* USE_SSL_ENGINE */
1000 /* PGSSLKEY is not an engine, treat it as a filename */
1001 strncpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1006 /* No PGSSLKEY specified, load default file */
1007 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1010 if (have_cert && fnbuf[0] != '\0')
1012 /* read the client key from file */
1014 if (stat(fnbuf, &buf) != 0)
1016 printfPQExpBuffer(&conn->errorMessage,
1017 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1022 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1024 printfPQExpBuffer(&conn->errorMessage,
1025 libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1031 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1033 char *err = SSLerrmessage();
1035 printfPQExpBuffer(&conn->errorMessage,
1036 libpq_gettext("could not load private key file \"%s\": %s\n"),
1043 /* verify that the cert and key go together */
1045 SSL_check_private_key(conn->ssl) != 1)
1047 char *err = SSLerrmessage();
1049 printfPQExpBuffer(&conn->errorMessage,
1050 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1057 * If the root cert file exists, load it so we can perform certificate
1058 * verification. If sslmode is "verify-full" we will also do further
1059 * verification after the connection has been completed.
1061 if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1062 strncpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1064 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1066 if (stat(fnbuf, &buf) == 0)
1068 X509_STORE *cvstore;
1070 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1072 char *err = SSLerrmessage();
1074 printfPQExpBuffer(&conn->errorMessage,
1075 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1081 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1083 if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1084 strncpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
1086 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1088 /* Set the flags to check against the complete CRL chain */
1089 if (X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
1091 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
1092 #ifdef X509_V_FLAG_CRL_CHECK
1093 X509_STORE_set_flags(cvstore,
1094 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1096 char *err = SSLerrmessage();
1098 printfPQExpBuffer(&conn->errorMessage,
1099 libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
1105 /* if not found, silently ignore; we do not require CRL */
1108 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1113 * stat() failed; assume root file doesn't exist. If sslmode is
1114 * verify-ca or verify-full, this is an error. Otherwise, continue
1115 * without performing any server cert verification.
1117 if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1119 printfPQExpBuffer(&conn->errorMessage,
1120 libpq_gettext("root certificate file \"%s\" does not exist\n"
1121 "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1132 destroy_ssl_system();
1136 * Attempt to negotiate SSL connection.
1138 static PostgresPollingStatusType
1139 open_client_SSL(PGconn *conn)
1143 r = SSL_connect(conn->ssl);
1146 int err = SSL_get_error(conn->ssl, r);
1150 case SSL_ERROR_WANT_READ:
1151 return PGRES_POLLING_READING;
1153 case SSL_ERROR_WANT_WRITE:
1154 return PGRES_POLLING_WRITING;
1156 case SSL_ERROR_SYSCALL:
1161 printfPQExpBuffer(&conn->errorMessage,
1162 libpq_gettext("SSL SYSCALL error: %s\n"),
1163 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1165 printfPQExpBuffer(&conn->errorMessage,
1166 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1168 return PGRES_POLLING_FAILED;
1172 char *err = SSLerrmessage();
1174 printfPQExpBuffer(&conn->errorMessage,
1175 libpq_gettext("SSL error: %s\n"),
1179 return PGRES_POLLING_FAILED;
1183 printfPQExpBuffer(&conn->errorMessage,
1184 libpq_gettext("unrecognized SSL error code: %d\n"),
1187 return PGRES_POLLING_FAILED;
1192 * We already checked the server certificate in initialize_SSL() using
1193 * SSL_CTX_set_verify(), if root.crt exists.
1196 /* pull out server distinguished and common names */
1197 conn->peer = SSL_get_peer_certificate(conn->ssl);
1198 if (conn->peer == NULL)
1200 char *err = SSLerrmessage();
1202 printfPQExpBuffer(&conn->errorMessage,
1203 libpq_gettext("certificate could not be obtained: %s\n"),
1207 return PGRES_POLLING_FAILED;
1210 X509_NAME_oneline(X509_get_subject_name(conn->peer),
1211 conn->peer_dn, sizeof(conn->peer_dn));
1212 conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
1214 r = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
1215 NID_commonName, conn->peer_cn, SM_USER);
1216 conn->peer_cn[SM_USER] = '\0'; /* buffer is SM_USER+1 chars! */
1219 /* Unable to get the CN, set it to blank so it can't be used */
1220 conn->peer_cn[0] = '\0';
1225 * Reject embedded NULLs in certificate common name to prevent attacks
1226 * like CVE-2009-4034.
1228 if (r != strlen(conn->peer_cn))
1230 printfPQExpBuffer(&conn->errorMessage,
1231 libpq_gettext("SSL certificate's common name contains embedded null\n"));
1233 return PGRES_POLLING_FAILED;
1237 if (!verify_peer_name_matches_certificate(conn))
1240 return PGRES_POLLING_FAILED;
1243 /* SSL handshake is complete */
1244 return PGRES_POLLING_OK;
1248 * Close SSL connection.
1251 close_SSL(PGconn *conn)
1255 DECLARE_SIGPIPE_INFO(spinfo);
1257 DISABLE_SIGPIPE(conn, spinfo, (void) 0);
1258 SSL_shutdown(conn->ssl);
1259 SSL_free(conn->ssl);
1262 /* We have to assume we got EPIPE */
1263 REMEMBER_EPIPE(spinfo, true);
1264 RESTORE_SIGPIPE(conn, spinfo);
1269 X509_free(conn->peer);
1273 #ifdef USE_SSL_ENGINE
1276 ENGINE_finish(conn->engine);
1277 ENGINE_free(conn->engine);
1278 conn->engine = NULL;
1284 * Obtain reason string for last SSL error
1286 * Some caution is needed here since ERR_reason_error_string will
1287 * return NULL if it doesn't recognize the error code. We don't
1288 * want to return NULL ever.
1290 static char ssl_nomem[] = "out of memory allocating error description";
1292 #define SSL_ERR_LEN 128
1297 unsigned long errcode;
1298 const char *errreason;
1301 errbuf = malloc(SSL_ERR_LEN);
1304 errcode = ERR_get_error();
1307 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1310 errreason = ERR_reason_error_string(errcode);
1311 if (errreason != NULL)
1313 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1316 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
1321 SSLerrfree(char *buf)
1323 if (buf != ssl_nomem)
1328 * Return pointer to OpenSSL object.
1331 PQgetssl(PGconn *conn)
1337 #else /* !USE_SSL */
1340 PQgetssl(PGconn *conn)
1344 #endif /* USE_SSL */
1347 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
1350 * Block SIGPIPE for this thread. This prevents send()/write() from exiting
1354 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1356 sigset_t sigpipe_sigset;
1359 sigemptyset(&sigpipe_sigset);
1360 sigaddset(&sigpipe_sigset, SIGPIPE);
1362 /* Block SIGPIPE and save previous mask for later reset */
1363 SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
1367 /* We can have a pending SIGPIPE only if it was blocked before */
1368 if (sigismember(osigset, SIGPIPE))
1370 /* Is there a pending SIGPIPE? */
1371 if (sigpending(&sigset) != 0)
1374 if (sigismember(&sigset, SIGPIPE))
1375 *sigpipe_pending = true;
1377 *sigpipe_pending = false;
1380 *sigpipe_pending = false;
1386 * Discard any pending SIGPIPE and reset the signal mask.
1388 * Note: we are effectively assuming here that the C library doesn't queue
1389 * up multiple SIGPIPE events. If it did, then we'd accidentally leave
1390 * ours in the queue when an event was already pending and we got another.
1391 * As long as it doesn't queue multiple events, we're OK because the caller
1392 * can't tell the difference.
1394 * The caller should say got_epipe = FALSE if it is certain that it
1395 * didn't get an EPIPE error; in that case we'll skip the clear operation
1396 * and things are definitely OK, queuing or no. If it got one or might have
1397 * gotten one, pass got_epipe = TRUE.
1399 * We do not want this to change errno, since if it did that could lose
1400 * the error code from a preceding send(). We essentially assume that if
1401 * we were able to do pq_block_sigpipe(), this can't fail.
1404 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1406 int save_errno = SOCK_ERRNO;
1410 /* Clear SIGPIPE only if none was pending */
1411 if (got_epipe && !sigpipe_pending)
1413 if (sigpending(&sigset) == 0 &&
1414 sigismember(&sigset, SIGPIPE))
1416 sigset_t sigpipe_sigset;
1418 sigemptyset(&sigpipe_sigset);
1419 sigaddset(&sigpipe_sigset, SIGPIPE);
1421 sigwait(&sigpipe_sigset, &signo);
1425 /* Restore saved block mask */
1426 pthread_sigmask(SIG_SETMASK, osigset, NULL);
1428 SOCK_ERRNO_SET(save_errno);
1431 #endif /* ENABLE_THREAD_SAFETY && !WIN32 */