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-2009, 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.119 2009/01/28 15:06:47 mha Exp $
18 * We don't provide informational callbacks here (like
19 * info_cb() in be-secure.c), since there's mechanism to
20 * display that information to the client.
22 *-------------------------------------------------------------------------
25 #include "postgres_fe.h"
38 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #ifdef HAVE_NETINET_TCP_H
43 #include <netinet/tcp.h>
45 #include <arpa/inet.h>
50 #ifdef ENABLE_THREAD_SAFETY
52 #include "pthread-win32.h"
60 #include <openssl/ssl.h>
61 #include <openssl/bio.h>
62 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L)
63 #include <openssl/conf.h>
65 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L) && !defined(OPENSSL_NO_ENGINE)
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 #ifndef HAVE_ERR_SET_MARK
84 /* These don't exist in OpenSSL before 0.9.8 */
85 #define ERR_set_mark() ((void) 0)
86 #define ERR_pop_to_mark() ((void) 0)
89 static bool verify_peer_name_matches_certificate(PGconn *);
90 static int verify_cb(int ok, X509_STORE_CTX *ctx);
91 static int client_cert_cb(SSL *, X509 **, EVP_PKEY **);
92 static int init_ssl_system(PGconn *conn);
93 static void destroy_ssl_system(void);
94 static int initialize_SSL(PGconn *);
95 static void destroySSL(void);
96 static PostgresPollingStatusType open_client_SSL(PGconn *);
97 static void close_SSL(PGconn *);
98 static char *SSLerrmessage(void);
99 static void SSLerrfree(char *buf);
101 static bool pq_initssllib = true;
102 static SSL_CTX *SSL_context = NULL;
104 #ifdef ENABLE_THREAD_SAFETY
105 static int ssl_open_connections = 0;
108 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
110 static pthread_mutex_t ssl_config_mutex = NULL;
111 static long win32_ssl_create_mutex = 0;
114 #endif /* ENABLE_THREAD_SAFETY */
120 * Macros to handle disabling and then restoring the state of SIGPIPE handling.
121 * Note that DISABLE_SIGPIPE() must appear at the start of a block.
125 #ifdef ENABLE_THREAD_SAFETY
127 #define DISABLE_SIGPIPE(failaction) \
129 bool sigpipe_pending; \
130 bool got_epipe = false; \
132 if (pq_block_sigpipe(&osigmask, &sigpipe_pending) < 0) \
135 #define REMEMBER_EPIPE(cond) \
141 #define RESTORE_SIGPIPE() \
142 pq_reset_sigpipe(&osigmask, sigpipe_pending, got_epipe)
144 #else /* !ENABLE_THREAD_SAFETY */
146 #define DISABLE_SIGPIPE(failaction) \
147 pqsigfunc oldsighandler = pqsignal(SIGPIPE, SIG_IGN)
149 #define REMEMBER_EPIPE(cond)
151 #define RESTORE_SIGPIPE() \
152 pqsignal(SIGPIPE, oldsighandler)
154 #endif /* ENABLE_THREAD_SAFETY */
157 #define DISABLE_SIGPIPE(failaction)
158 #define REMEMBER_EPIPE(cond)
159 #define RESTORE_SIGPIPE()
163 /* ------------------------------------------------------------ */
164 /* Procedures common to all secure sessions */
165 /* ------------------------------------------------------------ */
169 * Exported function to allow application to tell us it's already
170 * initialized OpenSSL.
173 PQinitSSL(int do_init)
176 pq_initssllib = do_init;
181 * Initialize global context
184 pqsecure_initialize(PGconn *conn)
189 r = initialize_SSL(conn);
196 * Destroy global context
199 pqsecure_destroy(void)
207 * Attempt to negotiate secure session.
209 PostgresPollingStatusType
210 pqsecure_open_client(PGconn *conn)
213 /* First time through? */
214 if (conn->ssl == NULL)
216 if (!(conn->ssl = SSL_new(SSL_context)) ||
217 !SSL_set_app_data(conn->ssl, conn) ||
218 !SSL_set_fd(conn->ssl, conn->sock))
220 char *err = SSLerrmessage();
222 printfPQExpBuffer(&conn->errorMessage,
223 libpq_gettext("could not establish SSL connection: %s\n"),
227 return PGRES_POLLING_FAILED;
231 * Initialize errorMessage to empty. This allows open_client_SSL() to
232 * detect whether client_cert_cb() has stored a message.
234 resetPQExpBuffer(&conn->errorMessage);
236 /* Begin or continue the actual handshake */
237 return open_client_SSL(conn);
239 /* shouldn't get here */
240 return PGRES_POLLING_FAILED;
245 * Close secure session.
248 pqsecure_close(PGconn *conn)
257 * Read data from a secure connection.
260 pqsecure_read(PGconn *conn, void *ptr, size_t len)
269 /* SSL_read can write to the socket, so we need to disable SIGPIPE */
270 DISABLE_SIGPIPE(return -1);
273 n = SSL_read(conn->ssl, ptr, len);
274 err = SSL_get_error(conn->ssl, n);
279 case SSL_ERROR_WANT_READ:
282 case SSL_ERROR_WANT_WRITE:
285 * Returning 0 here would cause caller to wait for read-ready,
286 * which is not correct since what SSL wants is wait for
287 * write-ready. The former could get us stuck in an infinite
288 * wait, so don't risk it; busy-loop instead.
291 case SSL_ERROR_SYSCALL:
297 REMEMBER_EPIPE(SOCK_ERRNO == EPIPE);
298 printfPQExpBuffer(&conn->errorMessage,
299 libpq_gettext("SSL SYSCALL error: %s\n"),
300 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
304 printfPQExpBuffer(&conn->errorMessage,
305 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
307 SOCK_ERRNO_SET(ECONNRESET);
314 char *err = SSLerrmessage();
316 printfPQExpBuffer(&conn->errorMessage,
317 libpq_gettext("SSL error: %s\n"), err);
321 case SSL_ERROR_ZERO_RETURN:
322 SOCK_ERRNO_SET(ECONNRESET);
326 printfPQExpBuffer(&conn->errorMessage,
327 libpq_gettext("unrecognized SSL error code: %d\n"),
337 n = recv(conn->sock, ptr, len, 0);
343 * Write data to a secure connection.
346 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
350 DISABLE_SIGPIPE(return -1);
357 n = SSL_write(conn->ssl, ptr, len);
358 err = SSL_get_error(conn->ssl, n);
363 case SSL_ERROR_WANT_READ:
366 * Returning 0 here causes caller to wait for write-ready,
367 * which is not really the right thing, but it's the best we
372 case SSL_ERROR_WANT_WRITE:
375 case SSL_ERROR_SYSCALL:
381 REMEMBER_EPIPE(SOCK_ERRNO == EPIPE);
382 printfPQExpBuffer(&conn->errorMessage,
383 libpq_gettext("SSL SYSCALL error: %s\n"),
384 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
388 printfPQExpBuffer(&conn->errorMessage,
389 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
390 SOCK_ERRNO_SET(ECONNRESET);
397 char *err = SSLerrmessage();
399 printfPQExpBuffer(&conn->errorMessage,
400 libpq_gettext("SSL error: %s\n"), err);
404 case SSL_ERROR_ZERO_RETURN:
405 SOCK_ERRNO_SET(ECONNRESET);
409 printfPQExpBuffer(&conn->errorMessage,
410 libpq_gettext("unrecognized SSL error code: %d\n"),
419 n = send(conn->sock, ptr, len, 0);
420 REMEMBER_EPIPE(n < 0 && SOCK_ERRNO == EPIPE);
428 /* ------------------------------------------------------------ */
429 /* SSL specific code */
430 /* ------------------------------------------------------------ */
434 * Certificate verification callback
436 * This callback allows us to log intermediate problems during
437 * verification, but there doesn't seem to be a clean way to get
438 * our PGconn * structure. So we can't log anything!
440 * This callback also allows us to override the default acceptance
441 * criteria (e.g., accepting self-signed or expired certs), but
442 * for now we accept the default checks.
445 verify_cb(int ok, X509_STORE_CTX *ctx)
452 * Check if a wildcard certificate matches the server hostname.
454 * The rule for this is:
455 * 1. We only match the '*' character as wildcard
456 * 2. We match only wildcards at the start of the string
457 * 3. The '*' character does *not* match '.', meaning that we match only
458 * a single pathname component.
459 * 4. We don't support more than one '*' in a single pattern.
461 * This is roughly in line with RFC2818, but contrary to what most browsers
462 * appear to be implementing (point 3 being the difference)
464 * Matching is always cone case-insensitive, since DNS is case insensitive.
467 wildcard_certificate_match(const char *pattern, const char *string)
469 int lenpat = strlen(pattern);
470 int lenstr = strlen(string);
472 /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
479 /* If pattern is longer than the string, we can never match */
482 if (pg_strcasecmp(pattern+1, string+lenstr-lenpat+1) != 0)
483 /* If string does not end in pattern (minus the wildcard), we don't match */
486 if (strchr(string, '.') < string+lenstr-lenpat)
487 /* If there is a dot left of where the pattern started to match, we don't match (rule 3) */
490 /* String ended with pattern, and didn't have a dot before, so we match */
496 * Verify that common name resolves to peer.
499 verify_peer_name_matches_certificate(PGconn *conn)
502 * If told not to verify the peer name, don't do it. Return
503 * 0 indicating that the verification was successful.
505 if(strcmp(conn->sslverify, "cn") != 0)
508 if (conn->pghostaddr)
510 printfPQExpBuffer(&conn->errorMessage,
511 libpq_gettext("verified SSL connections are only supported when connecting to a host name"));
517 * Connect by hostname.
519 * XXX: Should support alternate names here
521 if (pg_strcasecmp(conn->peer_cn, conn->pghost) == 0)
522 /* Exact name match */
524 else if (wildcard_certificate_match(conn->peer_cn, conn->pghost))
525 /* Matched wildcard certificate */
529 printfPQExpBuffer(&conn->errorMessage,
530 libpq_gettext("server common name \"%s\" does not match host name \"%s\""),
531 conn->peer_cn, conn->pghost);
538 * Callback used by SSL to load client cert and key.
539 * This callback is only called when the server wants a
542 * Since BIO functions can set OpenSSL error codes, we must
543 * reset the OpenSSL error stack on *every* exit from this
544 * function once we've started using BIO.
546 * Must return 1 on success, 0 on no data or error.
549 client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
551 char homedir[MAXPGPATH];
558 char fnbuf[MAXPGPATH];
560 PGconn *conn = (PGconn *) SSL_get_app_data(ssl);
564 * If conn->sslcert or conn->sslkey is not set, we don't need the home
565 * directory to find the required files.
567 if (!conn->sslcert || !conn->sslkey)
569 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
571 printfPQExpBuffer(&conn->errorMessage,
572 libpq_gettext("could not get home directory to locate client certificate files"));
577 /* read the user certificate */
579 strncpy(fnbuf, conn->sslcert, sizeof(fnbuf));
581 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
584 * OpenSSL <= 0.9.8 lacks error stack handling, which means it's likely to
585 * report wrong error messages if access to the cert file fails. Do our
586 * own check for the readability of the file to catch the majority of such
587 * problems before OpenSSL gets involved.
589 #ifndef HAVE_ERR_SET_MARK
593 if ((fp2 = fopen(fnbuf, "r")) == NULL)
595 printfPQExpBuffer(&conn->errorMessage,
596 libpq_gettext("could not open certificate file \"%s\": %s\n"),
597 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
604 /* save OpenSSL error stack */
607 if ((bio = BIO_new_file(fnbuf, "r")) == NULL)
609 printfPQExpBuffer(&conn->errorMessage,
610 libpq_gettext("could not open certificate file \"%s\": %s\n"),
611 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
616 if (PEM_read_bio_X509(bio, x509, NULL, NULL) == NULL)
618 char *err = SSLerrmessage();
620 printfPQExpBuffer(&conn->errorMessage,
621 libpq_gettext("could not read certificate file \"%s\": %s\n"),
632 * Read the SSL key. If a key is specified, treat it as an engine:key combination
633 * if there is colon present - we don't support files with colon in the name. The
634 * exception is if the second character is a colon, in which case it can be a Windows
635 * filename with drive specification.
637 if (conn->sslkey && strlen(conn->sslkey) > 0)
639 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L) && !defined(OPENSSL_NO_ENGINE)
640 if (strchr(conn->sslkey, ':')
642 && conn->sslkey[1] != ':'
646 /* Colon, but not in second character, treat as engine:key */
648 char *engine_str = strdup(conn->sslkey);
649 char *engine_colon = strchr(engine_str, ':');
651 *engine_colon = '\0'; /* engine_str now has engine name */
652 engine_colon++; /* engine_colon now has key name */
654 engine_ptr = ENGINE_by_id(engine_str);
655 if (engine_ptr == NULL)
657 char *err = SSLerrmessage();
659 printfPQExpBuffer(&conn->errorMessage,
660 libpq_gettext("could not load SSL engine \"%s\": %s\n"),
668 *pkey = ENGINE_load_private_key(engine_ptr, engine_colon,
672 char *err = SSLerrmessage();
674 printfPQExpBuffer(&conn->errorMessage,
675 libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
676 engine_colon, engine_str, err);
684 fnbuf[0] = '\0'; /* indicate we're not going to load from a file */
687 #endif /* support for SSL engines */
689 /* PGSSLKEY is not an engine, treat it as a filename */
690 strncpy(fnbuf, conn->sslkey, sizeof(fnbuf));
695 /* No PGSSLKEY specified, load default file */
696 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
699 if (fnbuf[0] != '\0')
701 /* read the user key from file */
703 if (stat(fnbuf, &buf) != 0)
705 printfPQExpBuffer(&conn->errorMessage,
706 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
712 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
714 printfPQExpBuffer(&conn->errorMessage,
715 libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
722 if ((bio = BIO_new_file(fnbuf, "r")) == NULL)
724 printfPQExpBuffer(&conn->errorMessage,
725 libpq_gettext("could not open private key file \"%s\": %s\n"),
726 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
731 BIO_get_fp(bio, &fp);
732 if (fstat(fileno(fp), &buf2) == -1 ||
733 buf.st_dev != buf2.st_dev || buf.st_ino != buf2.st_ino)
735 printfPQExpBuffer(&conn->errorMessage,
736 libpq_gettext("private key file \"%s\" changed during execution\n"), fnbuf);
742 if (PEM_read_bio_PrivateKey(bio, pkey, NULL, NULL) == NULL)
744 char *err = SSLerrmessage();
746 printfPQExpBuffer(&conn->errorMessage,
747 libpq_gettext("could not read private key file \"%s\": %s\n"),
759 /* verify that the cert and key go together */
760 if (X509_check_private_key(*x509, *pkey) != 1)
762 char *err = SSLerrmessage();
764 printfPQExpBuffer(&conn->errorMessage,
765 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
777 #ifdef ENABLE_THREAD_SAFETY
779 * Callback functions for OpenSSL internal locking
783 pq_threadidcallback(void)
786 * This is not standards-compliant. pthread_self() returns pthread_t, and
787 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
788 * it, so we have to do it.
790 return (unsigned long) pthread_self();
793 static pthread_mutex_t *pq_lockarray;
796 pq_lockingcallback(int mode, int n, const char *file, int line)
798 if (mode & CRYPTO_LOCK)
800 if (pthread_mutex_lock(&pq_lockarray[n]))
801 PGTHREAD_ERROR("failed to lock mutex");
805 if (pthread_mutex_unlock(&pq_lockarray[n]))
806 PGTHREAD_ERROR("failed to unlock mutex");
809 #endif /* ENABLE_THREAD_SAFETY */
812 * Initialize SSL system. In threadsafe mode, this includes setting
813 * up OpenSSL callback functions to do thread locking.
815 * If the caller has told us (through PQinitSSL) that he's taking care
816 * of SSL, we expect that callbacks are already set, and won't try to
819 * The conn parameter is only used to be able to pass back an error
820 * message - no connection local setup is made.
823 init_ssl_system(PGconn *conn)
825 #ifdef ENABLE_THREAD_SAFETY
827 /* Also see similar code in fe-connect.c, default_threadlock() */
828 if (ssl_config_mutex == NULL)
830 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
831 /* loop, another thread own the lock */ ;
832 if (ssl_config_mutex == NULL)
834 if (pthread_mutex_init(&ssl_config_mutex, NULL))
837 InterlockedExchange(&win32_ssl_create_mutex, 0);
840 if (pthread_mutex_lock(&ssl_config_mutex))
846 * If necessary, set up an array to hold locks for OpenSSL. OpenSSL will
847 * tell us how big to make this array.
849 if (pq_lockarray == NULL)
853 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
856 pthread_mutex_unlock(&ssl_config_mutex);
859 for (i = 0; i < CRYPTO_num_locks(); i++)
861 if (pthread_mutex_init(&pq_lockarray[i], NULL))
865 pthread_mutex_unlock(&ssl_config_mutex);
871 if (ssl_open_connections++ == 0)
873 /* These are only required for threaded SSL applications */
874 CRYPTO_set_id_callback(pq_threadidcallback);
875 CRYPTO_set_locking_callback(pq_lockingcallback);
878 #endif /* ENABLE_THREAD_SAFETY */
884 #if SSLEAY_VERSION_NUMBER >= 0x00907000L
885 OPENSSL_config(NULL);
888 SSL_load_error_strings();
890 SSL_context = SSL_CTX_new(TLSv1_method());
893 char *err = SSLerrmessage();
895 printfPQExpBuffer(&conn->errorMessage,
896 libpq_gettext("could not create SSL context: %s\n"),
899 #ifdef ENABLE_THREAD_SAFETY
900 pthread_mutex_unlock(&ssl_config_mutex);
906 #ifdef ENABLE_THREAD_SAFETY
907 pthread_mutex_unlock(&ssl_config_mutex);
913 * This function is needed because if the libpq library is unloaded
914 * from the application, the callback functions will no longer exist when
915 * SSL used by other parts of the system. For this reason,
916 * we unregister the SSL callback functions when the last libpq
917 * connection is closed.
919 * Callbacks are only set when we're compiled in threadsafe mode, so
920 * we only need to remove them in this case.
923 destroy_ssl_system(void)
925 #ifdef ENABLE_THREAD_SAFETY
926 /* Mutex is created in initialize_ssl_system() */
927 if (pthread_mutex_lock(&ssl_config_mutex))
932 if (ssl_open_connections > 0)
933 --ssl_open_connections;
935 if (ssl_open_connections == 0)
937 /* No connections left, unregister all callbacks */
938 CRYPTO_set_locking_callback(NULL);
939 CRYPTO_set_id_callback(NULL);
942 * We don't free the lock array. If we get another connection
943 * from the same caller, we will just re-use it with the existing
946 * This means we leak a little memory on repeated load/unload
952 pthread_mutex_unlock(&ssl_config_mutex);
958 * Initialize SSL context.
961 initialize_SSL(PGconn *conn)
964 char homedir[MAXPGPATH];
965 char fnbuf[MAXPGPATH];
967 if (init_ssl_system(conn))
971 * If sslverify is set to anything other than "none", perform certificate
972 * verification. If set to "cn" we will also do further verifications after
973 * the connection has been completed.
975 * If we are going to look for either root certificate or CRL in the home directory,
976 * we need pqGetHomeDirectory() to succeed. In other cases, we don't need to
977 * get the home directory explicitly.
979 if (!conn->sslrootcert || !conn->sslcrl)
981 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
983 if (strcmp(conn->sslverify, "none") != 0)
985 printfPQExpBuffer(&conn->errorMessage,
986 libpq_gettext("could not get home directory to locate root certificate file"));
998 if (conn->sslrootcert)
999 strncpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1001 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1003 if (stat(fnbuf, &buf) == 0)
1005 X509_STORE *cvstore;
1007 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1009 char *err = SSLerrmessage();
1011 printfPQExpBuffer(&conn->errorMessage,
1012 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1018 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1021 strncpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
1023 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1025 /* setting the flags to check against the complete CRL chain */
1026 if (X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
1027 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
1028 #ifdef X509_V_FLAG_CRL_CHECK
1029 X509_STORE_set_flags(cvstore,
1030 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1031 /* if not found, silently ignore; we do not require CRL */
1034 char *err = SSLerrmessage();
1036 printfPQExpBuffer(&conn->errorMessage,
1037 libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
1045 SSL_CTX_set_verify(SSL_context, SSL_VERIFY_PEER, verify_cb);
1049 /* stat() failed; assume cert file doesn't exist */
1050 if (strcmp(conn->sslverify, "none") != 0)
1052 printfPQExpBuffer(&conn->errorMessage,
1053 libpq_gettext("root certificate file \"%s\" does not exist"), fnbuf);
1058 /* set up mechanism to provide client certificate, if available */
1059 SSL_CTX_set_client_cert_cb(SSL_context, client_cert_cb);
1067 destroy_ssl_system();
1071 * Attempt to negotiate SSL connection.
1073 static PostgresPollingStatusType
1074 open_client_SSL(PGconn *conn)
1078 r = SSL_connect(conn->ssl);
1081 int err = SSL_get_error(conn->ssl, r);
1085 case SSL_ERROR_WANT_READ:
1086 return PGRES_POLLING_READING;
1088 case SSL_ERROR_WANT_WRITE:
1089 return PGRES_POLLING_WRITING;
1091 case SSL_ERROR_SYSCALL:
1096 printfPQExpBuffer(&conn->errorMessage,
1097 libpq_gettext("SSL SYSCALL error: %s\n"),
1098 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1100 printfPQExpBuffer(&conn->errorMessage,
1101 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1103 return PGRES_POLLING_FAILED;
1108 * If there are problems with the local certificate files,
1109 * these will be detected by client_cert_cb() which is
1110 * called from SSL_connect(). We want to return that
1111 * error message and not the rather unhelpful error that
1112 * OpenSSL itself returns. So check to see if an error
1113 * message was already stored.
1115 if (conn->errorMessage.len == 0)
1117 char *err = SSLerrmessage();
1119 printfPQExpBuffer(&conn->errorMessage,
1120 libpq_gettext("SSL error: %s\n"),
1125 return PGRES_POLLING_FAILED;
1129 printfPQExpBuffer(&conn->errorMessage,
1130 libpq_gettext("unrecognized SSL error code: %d\n"),
1133 return PGRES_POLLING_FAILED;
1138 * We already checked the server certificate in initialize_SSL()
1139 * using SSL_CTX_set_verify() if root.crt exists.
1142 /* pull out server distinguished and common names */
1143 conn->peer = SSL_get_peer_certificate(conn->ssl);
1144 if (conn->peer == NULL)
1146 char *err = SSLerrmessage();
1148 printfPQExpBuffer(&conn->errorMessage,
1149 libpq_gettext("certificate could not be obtained: %s\n"),
1153 return PGRES_POLLING_FAILED;
1156 X509_NAME_oneline(X509_get_subject_name(conn->peer),
1157 conn->peer_dn, sizeof(conn->peer_dn));
1158 conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
1160 X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
1161 NID_commonName, conn->peer_cn, SM_USER);
1162 conn->peer_cn[SM_USER] = '\0';
1164 if (!verify_peer_name_matches_certificate(conn))
1167 return PGRES_POLLING_FAILED;
1170 /* SSL handshake is complete */
1171 return PGRES_POLLING_OK;
1175 * Close SSL connection.
1178 close_SSL(PGconn *conn)
1182 DISABLE_SIGPIPE((void) 0);
1183 SSL_shutdown(conn->ssl);
1184 SSL_free(conn->ssl);
1187 /* We have to assume we got EPIPE */
1188 REMEMBER_EPIPE(true);
1194 X509_free(conn->peer);
1200 * Obtain reason string for last SSL error
1202 * Some caution is needed here since ERR_reason_error_string will
1203 * return NULL if it doesn't recognize the error code. We don't
1204 * want to return NULL ever.
1206 static char ssl_nomem[] = "out of memory allocating error description";
1208 #define SSL_ERR_LEN 128
1213 unsigned long errcode;
1214 const char *errreason;
1217 errbuf = malloc(SSL_ERR_LEN);
1220 errcode = ERR_get_error();
1223 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1226 errreason = ERR_reason_error_string(errcode);
1227 if (errreason != NULL)
1229 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1232 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
1237 SSLerrfree(char *buf)
1239 if (buf != ssl_nomem)
1244 * Return pointer to OpenSSL object.
1247 PQgetssl(PGconn *conn)
1253 #else /* !USE_SSL */
1256 PQgetssl(PGconn *conn)
1260 #endif /* USE_SSL */
1263 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
1266 * Block SIGPIPE for this thread. This prevents send()/write() from exiting
1270 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1272 sigset_t sigpipe_sigset;
1275 sigemptyset(&sigpipe_sigset);
1276 sigaddset(&sigpipe_sigset, SIGPIPE);
1278 /* Block SIGPIPE and save previous mask for later reset */
1279 SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
1283 /* We can have a pending SIGPIPE only if it was blocked before */
1284 if (sigismember(osigset, SIGPIPE))
1286 /* Is there a pending SIGPIPE? */
1287 if (sigpending(&sigset) != 0)
1290 if (sigismember(&sigset, SIGPIPE))
1291 *sigpipe_pending = true;
1293 *sigpipe_pending = false;
1296 *sigpipe_pending = false;
1302 * Discard any pending SIGPIPE and reset the signal mask.
1304 * Note: we are effectively assuming here that the C library doesn't queue
1305 * up multiple SIGPIPE events. If it did, then we'd accidentally leave
1306 * ours in the queue when an event was already pending and we got another.
1307 * As long as it doesn't queue multiple events, we're OK because the caller
1308 * can't tell the difference.
1310 * The caller should say got_epipe = FALSE if it is certain that it
1311 * didn't get an EPIPE error; in that case we'll skip the clear operation
1312 * and things are definitely OK, queuing or no. If it got one or might have
1313 * gotten one, pass got_epipe = TRUE.
1315 * We do not want this to change errno, since if it did that could lose
1316 * the error code from a preceding send(). We essentially assume that if
1317 * we were able to do pq_block_sigpipe(), this can't fail.
1320 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1322 int save_errno = SOCK_ERRNO;
1326 /* Clear SIGPIPE only if none was pending */
1327 if (got_epipe && !sigpipe_pending)
1329 if (sigpending(&sigset) == 0 &&
1330 sigismember(&sigset, SIGPIPE))
1332 sigset_t sigpipe_sigset;
1334 sigemptyset(&sigpipe_sigset);
1335 sigaddset(&sigpipe_sigset, SIGPIPE);
1337 sigwait(&sigpipe_sigset, &signo);
1341 /* Restore saved block mask */
1342 pthread_sigmask(SIG_SETMASK, osigset, NULL);
1344 SOCK_ERRNO_SET(save_errno);
1347 #endif /* ENABLE_THREAD_SAFETY && !WIN32 */