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-2006, 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.75 2006/03/05 15:59:09 momjian Exp $
17 * [ Most of these notes are wrong/obsolete, but perhaps not all ]
19 * The client *requires* a valid server certificate. Since
20 * SSH tunnels provide anonymous confidentiality, the presumption
21 * is that sites that want endpoint authentication will use the
22 * direct SSL support, while sites that are comfortable with
23 * anonymous connections will use SSH tunnels.
25 * This code verifies the server certificate, to detect simple
26 * "man-in-the-middle" and "impersonation" attacks. The
27 * server certificate, or better yet the CA certificate used
28 * to sign the server certificate, should be present in the
29 * "~/.postgresql/root.crt" file. If this file isn't
30 * readable, or the server certificate can't be validated,
31 * pqsecure_open_client() will return an error code.
33 * Additionally, the server certificate's "common name" must
34 * resolve to the other end of the socket. This makes it
35 * substantially harder to pull off a "man-in-the-middle" or
36 * "impersonation" attack even if the server's private key
37 * has been stolen. This check limits acceptable network
38 * layers to Unix sockets (weird, but legal), TCPv4 and TCPv6.
40 * Unfortunately neither the current front- or back-end handle
41 * failure gracefully, resulting in the backend hiccupping.
42 * This points out problems in each (the frontend shouldn't even
43 * try to do SSL if pqsecure_initialize() fails, and the backend
44 * shouldn't crash/recover if an SSH negotiation fails. The
45 * backend definitely needs to be fixed, to prevent a "denial
46 * of service" attack, but I don't know enough about how the
47 * backend works (especially that pre-SSL negotiation) to identify
52 * Unlike the server's static private key, the client's
53 * static private key (~/.postgresql/postgresql.key)
54 * should normally be stored encrypted. However we still
55 * support EPH since it's useful for other reasons.
59 * Client certificates are supported, if the server requests
60 * or requires them. Client certificates can be used for
61 * authentication, to prevent sessions from being hijacked,
62 * or to allow "road warriors" to access the database while
63 * keeping it closed to everyone else.
65 * The user's certificate and private key are located in
66 * ~/.postgresql/postgresql.crt
68 * ~/.postgresql/postgresql.key
73 * We don't provide informational callbacks here (like
74 * info_cb() in be-secure.c), since there's mechanism to
75 * display that information to the client.
77 *-------------------------------------------------------------------------
80 #include "postgres_fe.h"
87 #include "libpq-int.h"
94 #include <sys/socket.h>
97 #include <netinet/in.h>
98 #ifdef HAVE_NETINET_TCP_H
99 #include <netinet/tcp.h>
101 #include <arpa/inet.h>
103 #include <sys/stat.h>
105 #ifdef ENABLE_THREAD_SAFETY
107 #include "pthread-win32.h"
118 #include <openssl/ssl.h>
119 #include <openssl/dh.h>
126 #define USERCERTFILE ".postgresql/postgresql.crt"
127 #define USERKEYFILE ".postgresql/postgresql.key"
128 #define ROOTCERTFILE ".postgresql/root.crt"
129 #define DHFILEPATTERN "%s/.postgresql/dh%d.pem"
131 /* On Windows, the "home" directory is already PostgreSQL-specific */
132 #define USERCERTFILE "postgresql.crt"
133 #define USERKEYFILE "postgresql.key"
134 #define ROOTCERTFILE "root.crt"
135 #define DHFILEPATTERN "%s/dh%d.pem"
139 static int verify_peer(PGconn *);
141 static int verify_cb(int ok, X509_STORE_CTX *ctx);
142 static DH *load_dh_file(int keylength);
143 static DH *load_dh_buffer(const char *, size_t);
144 static DH *tmp_dh_cb(SSL *s, int is_export, int keylength);
145 static int client_cert_cb(SSL *, X509 **, EVP_PKEY **);
146 static int init_ssl_system(PGconn *conn);
147 static int initialize_SSL(PGconn *);
148 static void destroy_SSL(void);
149 static PostgresPollingStatusType open_client_SSL(PGconn *);
150 static void close_SSL(PGconn *);
151 static char *SSLerrmessage(void);
152 static void SSLerrfree(char *buf);
156 static bool pq_initssllib = true;
158 static SSL_CTX *SSL_context = NULL;
161 /* ------------------------------------------------------------ */
162 /* Hardcoded values */
163 /* ------------------------------------------------------------ */
166 * Hardcoded DH parameters, used in empheral DH keying.
167 * As discussed above, EDH protects the confidentiality of
168 * sessions even if the static private key is compromised,
169 * so we are *highly* motivated to ensure that we can use
170 * EDH even if the user... or an attacker... deletes the
171 * ~/.postgresql/dh*.pem files.
173 * It's not critical that users have EPH keys, but it doesn't
174 * hurt and if it's missing someone will demand it, so....
178 static const char file_dh512[] =
179 "-----BEGIN DH PARAMETERS-----\n\
180 MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak\n\
181 XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC\n\
182 -----END DH PARAMETERS-----\n";
184 static const char file_dh1024[] =
185 "-----BEGIN DH PARAMETERS-----\n\
186 MIGHAoGBAPSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsY\n\
187 jY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6\n\
188 ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpL3jHAgEC\n\
189 -----END DH PARAMETERS-----\n";
191 static const char file_dh2048[] =
192 "-----BEGIN DH PARAMETERS-----\n\
193 MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
194 89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
195 T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
196 zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
197 Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
198 CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
199 -----END DH PARAMETERS-----\n";
201 static const char file_dh4096[] =
202 "-----BEGIN DH PARAMETERS-----\n\
203 MIICCAKCAgEA+hRyUsFN4VpJ1O8JLcCo/VWr19k3BCgJ4uk+d+KhehjdRqNDNyOQ\n\
204 l/MOyQNQfWXPeGKmOmIig6Ev/nm6Nf9Z2B1h3R4hExf+zTiHnvVPeRBhjdQi81rt\n\
205 Xeoh6TNrSBIKIHfUJWBh3va0TxxjQIs6IZOLeVNRLMqzeylWqMf49HsIXqbcokUS\n\
206 Vt1BkvLdW48j8PPv5DsKRN3tloTxqDJGo9tKvj1Fuk74A+Xda1kNhB7KFlqMyN98\n\
207 VETEJ6c7KpfOo30mnK30wqw3S8OtaIR/maYX72tGOno2ehFDkq3pnPtEbD2CScxc\n\
208 alJC+EL7RPk5c/tgeTvCngvc1KZn92Y//EI7G9tPZtylj2b56sHtMftIoYJ9+ODM\n\
209 sccD5Piz/rejE3Ome8EOOceUSCYAhXn8b3qvxVI1ddd1pED6FHRhFvLrZxFvBEM9\n\
210 ERRMp5QqOaHJkM+Dxv8Cj6MqrCbfC4u+ZErxodzuusgDgvZiLF22uxMZbobFWyte\n\
211 OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH\n\
212 AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL\n\
213 KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=\n\
214 -----END DH PARAMETERS-----\n";
217 /* ------------------------------------------------------------ */
218 /* Procedures common to all secure sessions */
219 /* ------------------------------------------------------------ */
223 * Exported function to allow application to tell us it's already
224 * initialized OpenSSL.
227 PQinitSSL(int do_init)
230 pq_initssllib = do_init;
235 * Initialize global context
238 pqsecure_initialize(PGconn *conn)
243 r = initialize_SSL(conn);
250 * Destroy global context
253 pqsecure_destroy(void)
261 * Attempt to negotiate secure session.
263 PostgresPollingStatusType
264 pqsecure_open_client(PGconn *conn)
267 /* First time through? */
268 if (conn->ssl == NULL)
270 if (!(conn->ssl = SSL_new(SSL_context)) ||
271 !SSL_set_app_data(conn->ssl, conn) ||
272 !SSL_set_fd(conn->ssl, conn->sock))
274 char *err = SSLerrmessage();
276 printfPQExpBuffer(&conn->errorMessage,
277 libpq_gettext("could not establish SSL connection: %s\n"),
281 return PGRES_POLLING_FAILED;
285 * Initialize errorMessage to empty. This allows open_client_SSL() to
286 * detect whether client_cert_cb() has stored a message.
288 resetPQExpBuffer(&conn->errorMessage);
290 /* Begin or continue the actual handshake */
291 return open_client_SSL(conn);
293 /* shouldn't get here */
294 return PGRES_POLLING_FAILED;
299 * Close secure session.
302 pqsecure_close(PGconn *conn)
311 * Read data from a secure connection.
314 pqsecure_read(PGconn *conn, void *ptr, size_t len)
324 n = SSL_read(conn->ssl, ptr, len);
325 err = SSL_get_error(conn->ssl, n);
330 case SSL_ERROR_WANT_READ:
333 case SSL_ERROR_WANT_WRITE:
336 * Returning 0 here would cause caller to wait for read-ready,
337 * which is not correct since what SSL wants is wait for
338 * write-ready. The former could get us stuck in an infinite
339 * wait, so don't risk it; busy-loop instead.
342 case SSL_ERROR_SYSCALL:
347 printfPQExpBuffer(&conn->errorMessage,
348 libpq_gettext("SSL SYSCALL error: %s\n"),
349 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
352 printfPQExpBuffer(&conn->errorMessage,
353 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
355 SOCK_ERRNO_SET(ECONNRESET);
362 char *err = SSLerrmessage();
364 printfPQExpBuffer(&conn->errorMessage,
365 libpq_gettext("SSL error: %s\n"), err);
369 case SSL_ERROR_ZERO_RETURN:
370 SOCK_ERRNO_SET(ECONNRESET);
374 printfPQExpBuffer(&conn->errorMessage,
375 libpq_gettext("unrecognized SSL error code: %d\n"),
383 n = recv(conn->sock, ptr, len, 0);
389 * Write data to a secure connection.
392 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
397 #ifdef ENABLE_THREAD_SAFETY
399 bool sigpipe_pending;
400 bool got_epipe = false;
403 if (pq_block_sigpipe(&osigmask, &sigpipe_pending) < 0)
406 pqsigfunc oldsighandler = pqsignal(SIGPIPE, SIG_IGN);
407 #endif /* ENABLE_THREAD_SAFETY */
415 n = SSL_write(conn->ssl, ptr, len);
416 err = SSL_get_error(conn->ssl, n);
421 case SSL_ERROR_WANT_READ:
424 * Returning 0 here causes caller to wait for write-ready,
425 * which is not really the right thing, but it's the best we
430 case SSL_ERROR_WANT_WRITE:
433 case SSL_ERROR_SYSCALL:
439 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
440 if (SOCK_ERRNO == EPIPE)
443 printfPQExpBuffer(&conn->errorMessage,
444 libpq_gettext("SSL SYSCALL error: %s\n"),
445 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
449 printfPQExpBuffer(&conn->errorMessage,
450 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
451 SOCK_ERRNO_SET(ECONNRESET);
458 char *err = SSLerrmessage();
460 printfPQExpBuffer(&conn->errorMessage,
461 libpq_gettext("SSL error: %s\n"), err);
465 case SSL_ERROR_ZERO_RETURN:
466 SOCK_ERRNO_SET(ECONNRESET);
470 printfPQExpBuffer(&conn->errorMessage,
471 libpq_gettext("unrecognized SSL error code: %d\n"),
480 n = send(conn->sock, ptr, len, 0);
481 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
482 if (n < 0 && SOCK_ERRNO == EPIPE)
488 #ifdef ENABLE_THREAD_SAFETY
489 pq_reset_sigpipe(&osigmask, sigpipe_pending, got_epipe);
491 pqsignal(SIGPIPE, oldsighandler);
492 #endif /* ENABLE_THREAD_SAFETY */
498 /* ------------------------------------------------------------ */
499 /* SSL specific code */
500 /* ------------------------------------------------------------ */
504 * Certificate verification callback
506 * This callback allows us to log intermediate problems during
507 * verification, but there doesn't seem to be a clean way to get
508 * our PGconn * structure. So we can't log anything!
510 * This callback also allows us to override the default acceptance
511 * criteria (e.g., accepting self-signed or expired certs), but
512 * for now we accept the default checks.
515 verify_cb(int ok, X509_STORE_CTX *ctx)
522 * Verify that common name resolves to peer.
525 verify_peer(PGconn *conn)
527 struct hostent *h = NULL;
528 struct sockaddr addr;
529 struct sockaddr_in *sin;
530 ACCEPT_TYPE_ARG3 len;
534 /* get the address on the other side of the socket */
536 if (getpeername(conn->sock, &addr, &len) == -1)
540 printfPQExpBuffer(&conn->errorMessage,
541 libpq_gettext("error querying socket: %s\n"),
542 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
546 /* weird, but legal case */
547 if (addr.sa_family == AF_UNIX)
551 struct hostent hpstr;
556 * Currently, pqGethostbyname() is used only on platforms that don't
557 * have getaddrinfo(). If you enable this function, you should
558 * convert the pqGethostbyname() function call to use getaddrinfo().
560 pqGethostbyname(conn->peer_cn, &hpstr, buf, sizeof(buf),
564 /* what do we know about the peer's common name? */
567 printfPQExpBuffer(&conn->errorMessage,
568 libpq_gettext("could not get information about host \"%s\": %s\n"),
569 conn->peer_cn, hstrerror(h_errno));
573 /* does the address match? */
574 switch (addr.sa_family)
577 sin = (struct sockaddr_in *) & addr;
578 for (s = h->h_addr_list; *s != NULL; s++)
580 if (!memcmp(&sin->sin_addr.s_addr, *s, h->h_length))
586 printfPQExpBuffer(&conn->errorMessage,
587 libpq_gettext("unsupported protocol\n"));
592 * the prior test should be definitive, but in practice it sometimes
593 * fails. So we also check the aliases.
595 for (s = h->h_aliases; *s != NULL; s++)
597 if (pg_strcasecmp(conn->peer_cn, *s) == 0)
601 /* generate protocol-aware error message */
602 switch (addr.sa_family)
605 sin = (struct sockaddr_in *) & addr;
606 l = ntohl(sin->sin_addr.s_addr);
607 printfPQExpBuffer(&conn->errorMessage,
609 "server common name \"%s\" does not resolve to %ld.%ld.%ld.%ld\n"),
610 conn->peer_cn, (l >> 24) % 0x100, (l >> 16) % 0x100,
611 (l >> 8) % 0x100, l % 0x100);
614 printfPQExpBuffer(&conn->errorMessage,
616 "server common name \"%s\" does not resolve to peer address\n"),
622 #endif /* NOT_USED */
625 * Load precomputed DH parameters.
627 * To prevent "downgrade" attacks, we perform a number of checks
628 * to verify that the DBA-generated DH parameters file contains
629 * what we expect it to contain.
632 load_dh_file(int keylength)
634 char homedir[MAXPGPATH];
635 char fnbuf[MAXPGPATH];
640 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
643 /* attempt to open file. It's not an error if it doesn't exist. */
644 snprintf(fnbuf, sizeof(fnbuf), DHFILEPATTERN, homedir, keylength);
646 if ((fp = fopen(fnbuf, "r")) == NULL)
649 /* flock(fileno(fp), LOCK_SH); */
650 dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
651 /* flock(fileno(fp), LOCK_UN); */
654 /* is the prime the correct size? */
655 if (dh != NULL && 8 * DH_size(dh) < keylength)
658 /* make sure the DH parameters are usable */
661 if (DH_check(dh, &codes))
663 if (codes & DH_CHECK_P_NOT_PRIME)
665 if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
666 (codes & DH_CHECK_P_NOT_SAFE_PRIME))
674 * Load hardcoded DH parameters.
676 * To prevent problems if the DH parameters files don't even
677 * exist, we can load DH parameters hardcoded into this file.
680 load_dh_buffer(const char *buffer, size_t len)
685 bio = BIO_new_mem_buf((char *) buffer, len);
688 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
695 * Generate an empheral DH key. Because this can take a long
696 * time to compute, we can use precomputed parameters of the
699 * Since few sites will bother to precompute these parameter
700 * files, we also provide a fallback to the parameters provided
701 * by the OpenSSL project.
703 * These values can be static (once loaded or computed) since
704 * the OpenSSL library can efficiently generate random keys from
705 * the information provided.
708 tmp_dh_cb(SSL *s, int is_export, int keylength)
711 static DH *dh = NULL;
712 static DH *dh512 = NULL;
713 static DH *dh1024 = NULL;
714 static DH *dh2048 = NULL;
715 static DH *dh4096 = NULL;
721 dh512 = load_dh_file(keylength);
723 dh512 = load_dh_buffer(file_dh512, sizeof file_dh512);
729 dh1024 = load_dh_file(keylength);
731 dh1024 = load_dh_buffer(file_dh1024, sizeof file_dh1024);
737 dh2048 = load_dh_file(keylength);
739 dh2048 = load_dh_buffer(file_dh2048, sizeof file_dh2048);
745 dh4096 = load_dh_file(keylength);
747 dh4096 = load_dh_buffer(file_dh4096, sizeof file_dh4096);
753 dh = load_dh_file(keylength);
757 /* this may take a long time, but it may be necessary... */
758 if (r == NULL || 8 * DH_size(r) < keylength)
759 r = DH_generate_parameters(keylength, DH_GENERATOR_2, NULL, NULL);
765 * Callback used by SSL to load client cert and key.
766 * This callback is only called when the server wants a
769 * Must return 1 on success, 0 on no data or error.
772 client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
774 char homedir[MAXPGPATH];
780 char fnbuf[MAXPGPATH];
782 PGconn *conn = (PGconn *) SSL_get_app_data(ssl);
783 int (*cb) () = NULL; /* how to read user password */
786 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
788 printfPQExpBuffer(&conn->errorMessage,
789 libpq_gettext("could not get user information\n"));
793 /* read the user certificate */
794 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USERCERTFILE);
795 if ((fp = fopen(fnbuf, "r")) == NULL)
797 printfPQExpBuffer(&conn->errorMessage,
798 libpq_gettext("could not open certificate file \"%s\": %s\n"),
799 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
802 if (PEM_read_X509(fp, x509, NULL, NULL) == NULL)
804 char *err = SSLerrmessage();
806 printfPQExpBuffer(&conn->errorMessage,
807 libpq_gettext("could not read certificate file \"%s\": %s\n"),
815 /* read the user key */
816 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USERKEYFILE);
817 if (stat(fnbuf, &buf) == -1)
819 printfPQExpBuffer(&conn->errorMessage,
820 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
825 if (!S_ISREG(buf.st_mode) || (buf.st_mode & 0077) ||
826 buf.st_uid != geteuid())
828 printfPQExpBuffer(&conn->errorMessage,
829 libpq_gettext("private key file \"%s\" has wrong permissions\n"),
834 if ((fp = fopen(fnbuf, "r")) == NULL)
836 printfPQExpBuffer(&conn->errorMessage,
837 libpq_gettext("could not open private key file \"%s\": %s\n"),
838 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
842 if (fstat(fileno(fp), &buf2) == -1 ||
843 buf.st_dev != buf2.st_dev || buf.st_ino != buf2.st_ino)
845 printfPQExpBuffer(&conn->errorMessage,
846 libpq_gettext("private key file \"%s\" changed during execution\n"), fnbuf);
850 if (PEM_read_PrivateKey(fp, pkey, cb, NULL) == NULL)
852 char *err = SSLerrmessage();
854 printfPQExpBuffer(&conn->errorMessage,
855 libpq_gettext("could not read private key file \"%s\": %s\n"),
863 /* verify that the cert and key go together */
864 if (!X509_check_private_key(*x509, *pkey))
866 char *err = SSLerrmessage();
868 printfPQExpBuffer(&conn->errorMessage,
869 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
878 #ifdef ENABLE_THREAD_SAFETY
881 pq_threadidcallback(void)
884 * This is not starndard-compliant. pthread_self() returns pthread_t, and
885 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
886 * it, so we have to do it.
888 return (unsigned long) pthread_self();
891 static pthread_mutex_t *pq_lockarray;
894 pq_lockingcallback(int mode, int n, const char *file, int line)
896 if (mode & CRYPTO_LOCK)
897 pthread_mutex_lock(&pq_lockarray[n]);
899 pthread_mutex_unlock(&pq_lockarray[n]);
901 #endif /* ENABLE_THREAD_SAFETY */
904 init_ssl_system(PGconn *conn)
906 #ifdef ENABLE_THREAD_SAFETY
908 static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
910 static pthread_mutex_t init_mutex = NULL;
911 static long mutex_initlock = 0;
913 if (init_mutex == NULL)
915 while (InterlockedExchange(&mutex_initlock, 1) == 1)
916 /* loop, another thread own the lock */ ;
917 if (init_mutex == NULL)
918 pthread_mutex_init(&init_mutex, NULL);
919 InterlockedExchange(&mutex_initlock, 0);
922 pthread_mutex_lock(&init_mutex);
924 if (pq_initssllib && pq_lockarray == NULL)
928 CRYPTO_set_id_callback(pq_threadidcallback);
930 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
933 pthread_mutex_unlock(&init_mutex);
936 for (i = 0; i < CRYPTO_num_locks(); i++)
937 pthread_mutex_init(&pq_lockarray[i], NULL);
939 CRYPTO_set_locking_callback(pq_lockingcallback);
947 SSL_load_error_strings();
949 SSL_context = SSL_CTX_new(TLSv1_method());
952 char *err = SSLerrmessage();
954 printfPQExpBuffer(&conn->errorMessage,
955 libpq_gettext("could not create SSL context: %s\n"),
958 #ifdef ENABLE_THREAD_SAFETY
959 pthread_mutex_unlock(&init_mutex);
964 #ifdef ENABLE_THREAD_SAFETY
965 pthread_mutex_unlock(&init_mutex);
971 * Initialize global SSL context.
974 initialize_SSL(PGconn *conn)
977 char homedir[MAXPGPATH];
978 char fnbuf[MAXPGPATH];
980 if (init_ssl_system(conn))
983 /* Set up to verify server cert, if root.crt is present */
984 if (pqGetHomeDirectory(homedir, sizeof(homedir)))
986 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOTCERTFILE);
987 if (stat(fnbuf, &buf) == 0)
989 if (!SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL))
991 char *err = SSLerrmessage();
993 printfPQExpBuffer(&conn->errorMessage,
994 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1000 SSL_CTX_set_verify(SSL_context, SSL_VERIFY_PEER, verify_cb);
1004 /* set up empheral DH keys */
1005 SSL_CTX_set_tmp_dh_callback(SSL_context, tmp_dh_cb);
1006 SSL_CTX_set_options(SSL_context, SSL_OP_SINGLE_DH_USE);
1008 /* set up mechanism to provide client certificate, if available */
1009 SSL_CTX_set_client_cert_cb(SSL_context, client_cert_cb);
1015 * Destroy global SSL context.
1022 SSL_CTX_free(SSL_context);
1028 * Attempt to negotiate SSL connection.
1030 static PostgresPollingStatusType
1031 open_client_SSL(PGconn *conn)
1035 r = SSL_connect(conn->ssl);
1038 int err = SSL_get_error(conn->ssl, r);
1042 case SSL_ERROR_WANT_READ:
1043 return PGRES_POLLING_READING;
1045 case SSL_ERROR_WANT_WRITE:
1046 return PGRES_POLLING_WRITING;
1048 case SSL_ERROR_SYSCALL:
1053 printfPQExpBuffer(&conn->errorMessage,
1054 libpq_gettext("SSL SYSCALL error: %s\n"),
1055 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1057 printfPQExpBuffer(&conn->errorMessage,
1058 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1060 return PGRES_POLLING_FAILED;
1065 * If there are problems with the local certificate files,
1066 * these will be detected by client_cert_cb() which is
1067 * called from SSL_connect(). We want to return that
1068 * error message and not the rather unhelpful error that
1069 * OpenSSL itself returns. So check to see if an error
1070 * message was already stored.
1072 if (conn->errorMessage.len == 0)
1074 char *err = SSLerrmessage();
1076 printfPQExpBuffer(&conn->errorMessage,
1077 libpq_gettext("SSL error: %s\n"),
1082 return PGRES_POLLING_FAILED;
1086 printfPQExpBuffer(&conn->errorMessage,
1087 libpq_gettext("unrecognized SSL error code: %d\n"),
1090 return PGRES_POLLING_FAILED;
1094 /* check the certificate chain of the server */
1097 /* CLIENT CERTIFICATES NOT REQUIRED bjm 2002-09-26 */
1100 * this eliminates simple man-in-the-middle attacks and simple
1103 r = SSL_get_verify_result(conn->ssl);
1106 printfPQExpBuffer(&conn->errorMessage,
1107 libpq_gettext("certificate could not be validated: %s\n"),
1108 X509_verify_cert_error_string(r));
1110 return PGRES_POLLING_FAILED;
1114 /* pull out server distinguished and common names */
1115 conn->peer = SSL_get_peer_certificate(conn->ssl);
1116 if (conn->peer == NULL)
1118 char *err = SSLerrmessage();
1120 printfPQExpBuffer(&conn->errorMessage,
1121 libpq_gettext("certificate could not be obtained: %s\n"),
1125 return PGRES_POLLING_FAILED;
1128 X509_NAME_oneline(X509_get_subject_name(conn->peer),
1129 conn->peer_dn, sizeof(conn->peer_dn));
1130 conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
1132 X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
1133 NID_commonName, conn->peer_cn, SM_USER);
1134 conn->peer_cn[SM_USER] = '\0';
1136 /* verify that the common name resolves to peer */
1139 /* CLIENT CERTIFICATES NOT REQUIRED bjm 2002-09-26 */
1142 * this is necessary to eliminate man-in-the-middle attacks and
1143 * impersonations where the attacker somehow learned the server's private
1146 if (verify_peer(conn) == -1)
1149 return PGRES_POLLING_FAILED;
1153 /* SSL handshake is complete */
1154 return PGRES_POLLING_OK;
1158 * Close SSL connection.
1161 close_SSL(PGconn *conn)
1165 SSL_shutdown(conn->ssl);
1166 SSL_free(conn->ssl);
1172 X509_free(conn->peer);
1178 * Obtain reason string for last SSL error
1180 * Some caution is needed here since ERR_reason_error_string will
1181 * return NULL if it doesn't recognize the error code. We don't
1182 * want to return NULL ever.
1184 static char ssl_nomem[] = "Out of memory allocating error description";
1186 #define SSL_ERR_LEN 128
1191 unsigned long errcode;
1192 const char *errreason;
1195 errbuf = malloc(SSL_ERR_LEN);
1198 errcode = ERR_get_error();
1201 strcpy(errbuf, "No SSL error reported");
1204 errreason = ERR_reason_error_string(errcode);
1205 if (errreason != NULL)
1207 strncpy(errbuf, errreason, SSL_ERR_LEN - 1);
1208 errbuf[SSL_ERR_LEN - 1] = '\0';
1211 snprintf(errbuf, SSL_ERR_LEN, "SSL error code %lu", errcode);
1216 SSLerrfree(char *buf)
1218 if (buf != ssl_nomem)
1223 * Return pointer to SSL object.
1226 PQgetssl(PGconn *conn)
1232 #else /* !USE_SSL */
1235 PQgetssl(PGconn *conn)
1239 #endif /* USE_SSL */
1241 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
1244 * Block SIGPIPE for this thread. This prevents send()/write() from exiting
1248 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1250 sigset_t sigpipe_sigset;
1253 sigemptyset(&sigpipe_sigset);
1254 sigaddset(&sigpipe_sigset, SIGPIPE);
1256 /* Block SIGPIPE and save previous mask for later reset */
1257 SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
1261 /* We can have a pending SIGPIPE only if it was blocked before */
1262 if (sigismember(osigset, SIGPIPE))
1264 /* Is there a pending SIGPIPE? */
1265 if (sigpending(&sigset) != 0)
1268 if (sigismember(&sigset, SIGPIPE))
1269 *sigpipe_pending = true;
1271 *sigpipe_pending = false;
1274 *sigpipe_pending = false;
1280 * Discard any pending SIGPIPE and reset the signal mask.
1282 * Note: we are effectively assuming here that the C library doesn't queue
1283 * up multiple SIGPIPE events. If it did, then we'd accidentally leave
1284 * ours in the queue when an event was already pending and we got another.
1285 * As long as it doesn't queue multiple events, we're OK because the caller
1286 * can't tell the difference.
1288 * The caller should say got_epipe = FALSE if it is certain that it
1289 * didn't get an EPIPE error; in that case we'll skip the clear operation
1290 * and things are definitely OK, queuing or no. If it got one or might have
1291 * gotten one, pass got_epipe = TRUE.
1293 * We do not want this to change errno, since if it did that could lose
1294 * the error code from a preceding send(). We essentially assume that if
1295 * we were able to do pq_block_sigpipe(), this can't fail.
1298 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1300 int save_errno = SOCK_ERRNO;
1304 /* Clear SIGPIPE only if none was pending */
1305 if (got_epipe && !sigpipe_pending)
1307 if (sigpending(&sigset) == 0 &&
1308 sigismember(&sigset, SIGPIPE))
1310 sigset_t sigpipe_sigset;
1312 sigemptyset(&sigpipe_sigset);
1313 sigaddset(&sigpipe_sigset, SIGPIPE);
1315 sigwait(&sigpipe_sigset, &signo);
1319 /* Restore saved block mask */
1320 pthread_sigmask(SIG_SETMASK, osigset, NULL);
1322 SOCK_ERRNO_SET(save_errno);
1325 #endif /* ENABLE_THREAD_SAFETY */