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-2004, 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.50 2004/09/23 13:20:45 momjian Exp $
17 * The client *requires* a valid server certificate. Since
18 * SSH tunnels provide anonymous confidentiality, the presumption
19 * is that sites that want endpoint authentication will use the
20 * direct SSL support, while sites that are comfortable with
21 * anonymous connections will use SSH tunnels.
23 * This code verifies the server certificate, to detect simple
24 * "man-in-the-middle" and "impersonation" attacks. The
25 * server certificate, or better yet the CA certificate used
26 * to sign the server certificate, should be present in the
27 * "$HOME/.postgresql/root.crt" file. If this file isn't
28 * readable, or the server certificate can't be validated,
29 * pqsecure_open_client() will return an error code.
31 * Additionally, the server certificate's "common name" must
32 * resolve to the other end of the socket. This makes it
33 * substantially harder to pull off a "man-in-the-middle" or
34 * "impersonation" attack even if the server's private key
35 * has been stolen. This check limits acceptable network
36 * layers to Unix sockets (weird, but legal), TCPv4 and TCPv6.
38 * Unfortunately neither the current front- or back-end handle
39 * failure gracefully, resulting in the backend hiccupping.
40 * This points out problems in each (the frontend shouldn't even
41 * try to do SSL if pqsecure_initialize() fails, and the backend
42 * shouldn't crash/recover if an SSH negotiation fails. The
43 * backend definitely needs to be fixed, to prevent a "denial
44 * of service" attack, but I don't know enough about how the
45 * backend works (especially that pre-SSL negotiation) to identify
50 * Unlike the server's static private key, the client's
51 * static private key ($HOME/.postgresql/postgresql.key)
52 * should normally be stored encrypted. However we still
53 * support EPH since it's useful for other reasons.
57 * Client certificates are supported, if the server requests
58 * or requires them. Client certificates can be used for
59 * authentication, to prevent sessions from being hijacked,
60 * or to allow "road warriors" to access the database while
61 * keeping it closed to everyone else.
63 * The user's certificate and private key are located in
64 * $HOME/.postgresql/postgresql.crt
66 * $HOME/.postgresql/postgresql.key
71 * We don't provide informational callbacks here (like
72 * info_cb() in be-secure.c), since there's mechanism to
73 * display that information to the client.
76 * The code currently assumes a POSIX password entry. How should
77 * Windows and Mac users be handled?
79 *-------------------------------------------------------------------------
82 #include "postgres_fe.h"
84 #include <sys/types.h>
92 #include "libpq-int.h"
99 #include <sys/socket.h>
102 #include <netinet/in.h>
103 #ifdef HAVE_NETINET_TCP_H
104 #include <netinet/tcp.h>
106 #include <arpa/inet.h>
109 #ifdef ENABLE_THREAD_SAFETY
120 #include <sys/stat.h>
123 #include <openssl/ssl.h>
124 #include <openssl/dh.h>
129 static int verify_cb(int ok, X509_STORE_CTX *ctx);
132 static int verify_peer(PGconn *);
134 static DH *load_dh_file(int keylength);
135 static DH *load_dh_buffer(const char *, size_t);
136 static DH *tmp_dh_cb(SSL *s, int is_export, int keylength);
137 static int client_cert_cb(SSL *, X509 **, EVP_PKEY **);
138 static int init_ssl_system(PGconn *conn);
139 static int initialize_SSL(PGconn *);
140 static void destroy_SSL(void);
141 static PostgresPollingStatusType open_client_SSL(PGconn *);
142 static void close_SSL(PGconn *);
143 static char *SSLerrmessage(void);
144 static void SSLerrfree(char *buf);
148 bool pq_initssllib = true;
150 static SSL_CTX *SSL_context = NULL;
153 #ifdef ENABLE_THREAD_SAFETY
154 static void sigpipe_handler_ignore_send(int signo);
155 pthread_key_t pq_thread_in_send = 0; /* initializer needed on Darwin */
156 static pqsigfunc pq_pipe_handler;
159 /* ------------------------------------------------------------ */
160 /* Hardcoded values */
161 /* ------------------------------------------------------------ */
164 * Hardcoded DH parameters, used in empheral DH keying.
165 * As discussed above, EDH protects the confidentiality of
166 * sessions even if the static private key is compromised,
167 * so we are *highly* motivated to ensure that we can use
168 * EDH even if the user... or an attacker... deletes the
169 * $HOME/.postgresql/dh*.pem files.
171 * It's not critical that users have EPH keys, but it doesn't
172 * hurt and if it's missing someone will demand it, so....
176 static const char file_dh512[] =
177 "-----BEGIN DH PARAMETERS-----\n\
178 MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak\n\
179 XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC\n\
180 -----END DH PARAMETERS-----\n";
182 static const char file_dh1024[] =
183 "-----BEGIN DH PARAMETERS-----\n\
184 MIGHAoGBAPSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsY\n\
185 jY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6\n\
186 ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpL3jHAgEC\n\
187 -----END DH PARAMETERS-----\n";
189 static const char file_dh2048[] =
190 "-----BEGIN DH PARAMETERS-----\n\
191 MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
192 89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
193 T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
194 zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
195 Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
196 CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
197 -----END DH PARAMETERS-----\n";
199 static const char file_dh4096[] =
200 "-----BEGIN DH PARAMETERS-----\n\
201 MIICCAKCAgEA+hRyUsFN4VpJ1O8JLcCo/VWr19k3BCgJ4uk+d+KhehjdRqNDNyOQ\n\
202 l/MOyQNQfWXPeGKmOmIig6Ev/nm6Nf9Z2B1h3R4hExf+zTiHnvVPeRBhjdQi81rt\n\
203 Xeoh6TNrSBIKIHfUJWBh3va0TxxjQIs6IZOLeVNRLMqzeylWqMf49HsIXqbcokUS\n\
204 Vt1BkvLdW48j8PPv5DsKRN3tloTxqDJGo9tKvj1Fuk74A+Xda1kNhB7KFlqMyN98\n\
205 VETEJ6c7KpfOo30mnK30wqw3S8OtaIR/maYX72tGOno2ehFDkq3pnPtEbD2CScxc\n\
206 alJC+EL7RPk5c/tgeTvCngvc1KZn92Y//EI7G9tPZtylj2b56sHtMftIoYJ9+ODM\n\
207 sccD5Piz/rejE3Ome8EOOceUSCYAhXn8b3qvxVI1ddd1pED6FHRhFvLrZxFvBEM9\n\
208 ERRMp5QqOaHJkM+Dxv8Cj6MqrCbfC4u+ZErxodzuusgDgvZiLF22uxMZbobFWyte\n\
209 OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH\n\
210 AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL\n\
211 KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=\n\
212 -----END DH PARAMETERS-----\n";
215 /* ------------------------------------------------------------ */
216 /* Procedures common to all secure sessions */
217 /* ------------------------------------------------------------ */
220 * Initialize global context
223 pqsecure_initialize(PGconn *conn)
228 r = initialize_SSL(conn);
235 * Destroy global context
238 pqsecure_destroy(void)
246 * Attempt to negotiate secure session.
248 PostgresPollingStatusType
249 pqsecure_open_client(PGconn *conn)
252 /* First time through? */
253 if (conn->ssl == NULL)
255 if (!(conn->ssl = SSL_new(SSL_context)) ||
256 !SSL_set_app_data(conn->ssl, conn) ||
257 !SSL_set_fd(conn->ssl, conn->sock))
259 char *err = SSLerrmessage();
261 printfPQExpBuffer(&conn->errorMessage,
262 libpq_gettext("could not establish SSL connection: %s\n"),
266 return PGRES_POLLING_FAILED;
269 /* Begin or continue the actual handshake */
270 return open_client_SSL(conn);
272 /* shouldn't get here */
273 return PGRES_POLLING_FAILED;
278 * Close secure session.
281 pqsecure_close(PGconn *conn)
290 * Read data from a secure connection.
293 pqsecure_read(PGconn *conn, void *ptr, size_t len)
301 n = SSL_read(conn->ssl, ptr, len);
302 switch (SSL_get_error(conn->ssl, n))
306 case SSL_ERROR_WANT_READ:
309 case SSL_ERROR_WANT_WRITE:
312 * Returning 0 here would cause caller to wait for
313 * read-ready, which is not correct since what SSL wants
314 * is wait for write-ready. The former could get us stuck
315 * in an infinite wait, so don't risk it; busy-loop
319 case SSL_ERROR_SYSCALL:
324 printfPQExpBuffer(&conn->errorMessage,
325 libpq_gettext("SSL SYSCALL error: %s\n"),
326 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
329 printfPQExpBuffer(&conn->errorMessage,
330 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
332 SOCK_ERRNO_SET(ECONNRESET);
339 char *err = SSLerrmessage();
341 printfPQExpBuffer(&conn->errorMessage,
342 libpq_gettext("SSL error: %s\n"), err);
346 case SSL_ERROR_ZERO_RETURN:
347 SOCK_ERRNO_SET(ECONNRESET);
351 printfPQExpBuffer(&conn->errorMessage,
352 libpq_gettext("unrecognized SSL error code\n"));
359 n = recv(conn->sock, ptr, len, 0);
365 * Write data to a secure connection.
368 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
372 #ifdef ENABLE_THREAD_SAFETY
373 pthread_setspecific(pq_thread_in_send, "t");
376 pqsigfunc oldsighandler = pqsignal(SIGPIPE, SIG_IGN);
383 n = SSL_write(conn->ssl, ptr, len);
384 switch (SSL_get_error(conn->ssl, n))
388 case SSL_ERROR_WANT_READ:
391 * Returning 0 here causes caller to wait for write-ready,
392 * which is not really the right thing, but it's the best
397 case SSL_ERROR_WANT_WRITE:
400 case SSL_ERROR_SYSCALL:
405 printfPQExpBuffer(&conn->errorMessage,
406 libpq_gettext("SSL SYSCALL error: %s\n"),
407 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
410 printfPQExpBuffer(&conn->errorMessage,
411 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
412 SOCK_ERRNO_SET(ECONNRESET);
419 char *err = SSLerrmessage();
421 printfPQExpBuffer(&conn->errorMessage,
422 libpq_gettext("SSL error: %s\n"), err);
426 case SSL_ERROR_ZERO_RETURN:
427 SOCK_ERRNO_SET(ECONNRESET);
431 printfPQExpBuffer(&conn->errorMessage,
432 libpq_gettext("unrecognized SSL error code\n"));
439 n = send(conn->sock, ptr, len, 0);
441 #ifdef ENABLE_THREAD_SAFETY
442 pthread_setspecific(pq_thread_in_send, "f");
445 pqsignal(SIGPIPE, oldsighandler);
452 /* ------------------------------------------------------------ */
453 /* SSL specific code */
454 /* ------------------------------------------------------------ */
457 * Certificate verification callback
459 * This callback allows us to log intermediate problems during
460 * verification, but there doesn't seem to be a clean way to get
461 * our PGconn * structure. So we can't log anything!
463 * This callback also allows us to override the default acceptance
464 * criteria (e.g., accepting self-signed or expired certs), but
465 * for now we accept the default checks.
468 verify_cb(int ok, X509_STORE_CTX *ctx)
475 * Verify that common name resolves to peer.
478 verify_peer(PGconn *conn)
480 struct hostent *h = NULL;
481 struct sockaddr addr;
482 struct sockaddr_in *sin;
487 /* get the address on the other side of the socket */
489 if (getpeername(conn->sock, &addr, &len) == -1)
493 printfPQExpBuffer(&conn->errorMessage,
494 libpq_gettext("error querying socket: %s\n"),
495 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
499 /* weird, but legal case */
500 if (addr.sa_family == AF_UNIX)
504 struct hostent hpstr;
509 * Currently, pqGethostbyname() is used only on platforms that
510 * don't have getaddrinfo(). If you enable this function, you
511 * should convert the pqGethostbyname() function call to use
514 pqGethostbyname(conn->peer_cn, &hpstr, buf, sizeof(buf),
518 /* what do we know about the peer's common name? */
521 printfPQExpBuffer(&conn->errorMessage,
522 libpq_gettext("could not get information about host (%s): %s\n"),
523 conn->peer_cn, hstrerror(h_errno));
527 /* does the address match? */
528 switch (addr.sa_family)
531 sin = (struct sockaddr_in *) & addr;
532 for (s = h->h_addr_list; *s != NULL; s++)
534 if (!memcmp(&sin->sin_addr.s_addr, *s, h->h_length))
540 printfPQExpBuffer(&conn->errorMessage,
541 libpq_gettext("unsupported protocol\n"));
546 * the prior test should be definitive, but in practice it sometimes
547 * fails. So we also check the aliases.
549 for (s = h->h_aliases; *s != NULL; s++)
551 if (pg_strcasecmp(conn->peer_cn, *s) == 0)
555 /* generate protocol-aware error message */
556 switch (addr.sa_family)
559 sin = (struct sockaddr_in *) & addr;
560 l = ntohl(sin->sin_addr.s_addr);
561 printfPQExpBuffer(&conn->errorMessage,
563 "server common name \"%s\" does not resolve to %ld.%ld.%ld.%ld\n"),
564 conn->peer_cn, (l >> 24) % 0x100, (l >> 16) % 0x100,
565 (l >> 8) % 0x100, l % 0x100);
568 printfPQExpBuffer(&conn->errorMessage,
570 "server common name \"%s\" does not resolve to peer address\n"),
579 * Load precomputed DH parameters.
581 * To prevent "downgrade" attacks, we perform a number of checks
582 * to verify that the DBA-generated DH parameters file contains
583 * what we expect it to contain.
586 load_dh_file(int keylength)
592 struct passwd pwdstr;
593 struct passwd *pwd = NULL;
599 if (pqGetpwuid(getuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) == 0)
602 /* attempt to open file. It's not an error if it doesn't exist. */
603 snprintf(fnbuf, sizeof fnbuf, "%s/.postgresql/dh%d.pem",
604 pwd->pw_dir, keylength);
606 if ((fp = fopen(fnbuf, "r")) == NULL)
609 /* flock(fileno(fp), LOCK_SH); */
610 dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
611 /* flock(fileno(fp), LOCK_UN); */
614 /* is the prime the correct size? */
615 if (dh != NULL && 8 * DH_size(dh) < keylength)
618 /* make sure the DH parameters are usable */
621 if (DH_check(dh, &codes))
623 if (codes & DH_CHECK_P_NOT_PRIME)
625 if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
626 (codes & DH_CHECK_P_NOT_SAFE_PRIME))
635 * Load hardcoded DH parameters.
637 * To prevent problems if the DH parameters files don't even
638 * exist, we can load DH parameters hardcoded into this file.
641 load_dh_buffer(const char *buffer, size_t len)
646 bio = BIO_new_mem_buf((char *) buffer, len);
649 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
656 * Generate an empheral DH key. Because this can take a long
657 * time to compute, we can use precomputed parameters of the
660 * Since few sites will bother to precompute these parameter
661 * files, we also provide a fallback to the parameters provided
662 * by the OpenSSL project.
664 * These values can be static (once loaded or computed) since
665 * the OpenSSL library can efficiently generate random keys from
666 * the information provided.
669 tmp_dh_cb(SSL *s, int is_export, int keylength)
672 static DH *dh = NULL;
673 static DH *dh512 = NULL;
674 static DH *dh1024 = NULL;
675 static DH *dh2048 = NULL;
676 static DH *dh4096 = NULL;
682 dh512 = load_dh_file(keylength);
684 dh512 = load_dh_buffer(file_dh512, sizeof file_dh512);
690 dh1024 = load_dh_file(keylength);
692 dh1024 = load_dh_buffer(file_dh1024, sizeof file_dh1024);
698 dh2048 = load_dh_file(keylength);
700 dh2048 = load_dh_buffer(file_dh2048, sizeof file_dh2048);
706 dh4096 = load_dh_file(keylength);
708 dh4096 = load_dh_buffer(file_dh4096, sizeof file_dh4096);
714 dh = load_dh_file(keylength);
718 /* this may take a long time, but it may be necessary... */
719 if (r == NULL || 8 * DH_size(r) < keylength)
720 r = DH_generate_parameters(keylength, DH_GENERATOR_2, NULL, NULL);
726 * Callback used by SSL to load client cert and key.
727 * This callback is only called when the server wants a
730 * Returns 1 on success, 0 on no data, -1 on error.
733 client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
739 struct passwd pwdstr;
740 struct passwd *pwd = NULL;
745 PGconn *conn = (PGconn *) SSL_get_app_data(ssl);
746 int (*cb) () = NULL; /* how to read user password */
750 if (pqGetpwuid(getuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) == 0)
752 printfPQExpBuffer(&conn->errorMessage,
753 libpq_gettext("could not get user information\n"));
757 /* read the user certificate */
758 snprintf(fnbuf, sizeof fnbuf, "%s/.postgresql/postgresql.crt",
760 if (stat(fnbuf, &buf) == -1)
762 if ((fp = fopen(fnbuf, "r")) == NULL)
764 printfPQExpBuffer(&conn->errorMessage,
765 libpq_gettext("could not open certificate (%s): %s\n"),
766 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
769 if (PEM_read_X509(fp, x509, NULL, NULL) == NULL)
771 char *err = SSLerrmessage();
773 printfPQExpBuffer(&conn->errorMessage,
774 libpq_gettext("could not read certificate (%s): %s\n"),
782 /* read the user key */
783 snprintf(fnbuf, sizeof fnbuf, "%s/.postgresql/postgresql.key",
785 if (stat(fnbuf, &buf) == -1)
787 printfPQExpBuffer(&conn->errorMessage,
788 libpq_gettext("certificate present, but not private key (%s)\n"),
793 if (!S_ISREG(buf.st_mode) || (buf.st_mode & 0077) ||
794 buf.st_uid != getuid())
796 printfPQExpBuffer(&conn->errorMessage,
797 libpq_gettext("private key (%s) has wrong permissions\n"), fnbuf);
801 if ((fp = fopen(fnbuf, "r")) == NULL)
803 printfPQExpBuffer(&conn->errorMessage,
804 libpq_gettext("could not open private key file (%s): %s\n"),
805 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
809 if (fstat(fileno(fp), &buf2) == -1 ||
810 buf.st_dev != buf2.st_dev || buf.st_ino != buf2.st_ino)
812 printfPQExpBuffer(&conn->errorMessage,
813 libpq_gettext("private key (%s) changed during execution\n"), fnbuf);
817 if (PEM_read_PrivateKey(fp, pkey, cb, NULL) == NULL)
819 char *err = SSLerrmessage();
821 printfPQExpBuffer(&conn->errorMessage,
822 libpq_gettext("could not read private key (%s): %s\n"),
831 /* verify that the cert and key go together */
832 if (!X509_check_private_key(*x509, *pkey))
834 char *err = SSLerrmessage();
836 printfPQExpBuffer(&conn->errorMessage,
837 libpq_gettext("certificate/private key mismatch (%s): %s\n"),
841 EVP_PKEY_free(*pkey);
849 #ifdef ENABLE_THREAD_SAFETY
852 pq_threadidcallback(void)
854 return (unsigned long) pthread_self();
857 static pthread_mutex_t *pq_lockarray;
859 pq_lockingcallback(int mode, int n, const char *file, int line)
861 if (mode & CRYPTO_LOCK)
862 pthread_mutex_lock(&pq_lockarray[n]);
864 pthread_mutex_unlock(&pq_lockarray[n]);
866 #endif /* ENABLE_THREAD_SAFETY */
869 init_ssl_system(PGconn *conn)
871 #ifdef ENABLE_THREAD_SAFETY
873 static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
876 static pthread_mutex_t init_mutex = NULL;
877 static long mutex_initlock = 0;
879 if (init_mutex == NULL)
881 while (InterlockedExchange(&mutex_initlock, 1) == 1)
882 /* loop, another thread own the lock */ ;
883 if (init_mutex == NULL)
884 pthread_mutex_init(&init_mutex, NULL);
885 InterlockedExchange(&mutex_initlock, 0);
888 pthread_mutex_lock(&init_mutex);
890 if (pq_initssllib && pq_lockarray == NULL)
894 CRYPTO_set_id_callback(pq_threadidcallback);
896 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
899 pthread_mutex_unlock(&init_mutex);
902 for (i = 0; i < CRYPTO_num_locks(); i++)
903 pthread_mutex_init(&pq_lockarray[i], NULL);
905 CRYPTO_set_locking_callback(pq_lockingcallback);
913 SSL_load_error_strings();
915 SSL_context = SSL_CTX_new(TLSv1_method());
918 char *err = SSLerrmessage();
920 printfPQExpBuffer(&conn->errorMessage,
921 libpq_gettext("could not create SSL context: %s\n"),
924 #ifdef ENABLE_THREAD_SAFETY
925 pthread_mutex_unlock(&init_mutex);
930 #ifdef ENABLE_THREAD_SAFETY
931 pthread_mutex_unlock(&init_mutex);
937 * Initialize global SSL context.
940 initialize_SSL(PGconn *conn)
945 struct passwd pwdstr;
946 struct passwd *pwd = NULL;
950 if (init_ssl_system(conn))
954 if (pqGetpwuid(getuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) == 0)
956 snprintf(fnbuf, sizeof fnbuf, "%s/.postgresql/root.crt",
958 if (stat(fnbuf, &buf) == -1)
964 /* CLIENT CERTIFICATES NOT REQUIRED bjm 2002-09-26 */
965 printfPQExpBuffer(&conn->errorMessage,
966 libpq_gettext("could not read root certificate list (%s): %s\n"),
967 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
971 if (!SSL_CTX_load_verify_locations(SSL_context, fnbuf, 0))
973 char *err = SSLerrmessage();
975 printfPQExpBuffer(&conn->errorMessage,
976 libpq_gettext("could not read root certificate list (%s): %s\n"),
983 SSL_CTX_set_verify(SSL_context,
984 SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb);
985 SSL_CTX_set_verify_depth(SSL_context, 1);
987 /* set up empheral DH keys */
988 SSL_CTX_set_tmp_dh_callback(SSL_context, tmp_dh_cb);
989 SSL_CTX_set_options(SSL_context, SSL_OP_SINGLE_DH_USE);
991 /* set up mechanism to provide client certificate, if available */
992 SSL_CTX_set_client_cert_cb(SSL_context, client_cert_cb);
999 * Destroy global SSL context.
1006 SSL_CTX_free(SSL_context);
1012 * Attempt to negotiate SSL connection.
1014 static PostgresPollingStatusType
1015 open_client_SSL(PGconn *conn)
1019 r = SSL_connect(conn->ssl);
1022 int err = SSL_get_error(conn->ssl, r);
1025 case SSL_ERROR_WANT_READ:
1026 return PGRES_POLLING_READING;
1028 case SSL_ERROR_WANT_WRITE:
1029 return PGRES_POLLING_WRITING;
1031 case SSL_ERROR_SYSCALL:
1036 printfPQExpBuffer(&conn->errorMessage,
1037 libpq_gettext("SSL SYSCALL error: %s\n"),
1038 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1040 printfPQExpBuffer(&conn->errorMessage,
1041 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1043 return PGRES_POLLING_FAILED;
1047 char *err = SSLerrmessage();
1049 printfPQExpBuffer(&conn->errorMessage,
1050 libpq_gettext("SSL error: %s\n"), err);
1053 return PGRES_POLLING_FAILED;
1057 printfPQExpBuffer(&conn->errorMessage,
1058 libpq_gettext("unrecognized SSL error code (%d)\n"), err);
1060 return PGRES_POLLING_FAILED;
1064 /* check the certificate chain of the server */
1067 /* CLIENT CERTIFICATES NOT REQUIRED bjm 2002-09-26 */
1070 * this eliminates simple man-in-the-middle attacks and simple
1073 r = SSL_get_verify_result(conn->ssl);
1076 printfPQExpBuffer(&conn->errorMessage,
1077 libpq_gettext("certificate could not be validated: %s\n"),
1078 X509_verify_cert_error_string(r));
1080 return PGRES_POLLING_FAILED;
1084 /* pull out server distinguished and common names */
1085 conn->peer = SSL_get_peer_certificate(conn->ssl);
1086 if (conn->peer == NULL)
1088 char *err = SSLerrmessage();
1090 printfPQExpBuffer(&conn->errorMessage,
1091 libpq_gettext("certificate could not be obtained: %s\n"),
1095 return PGRES_POLLING_FAILED;
1098 X509_NAME_oneline(X509_get_subject_name(conn->peer),
1099 conn->peer_dn, sizeof(conn->peer_dn));
1100 conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
1102 X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
1103 NID_commonName, conn->peer_cn, SM_USER);
1104 conn->peer_cn[SM_USER] = '\0';
1106 /* verify that the common name resolves to peer */
1109 /* CLIENT CERTIFICATES NOT REQUIRED bjm 2002-09-26 */
1112 * this is necessary to eliminate man-in-the-middle attacks and
1113 * impersonations where the attacker somehow learned the server's
1116 if (verify_peer(conn) == -1)
1119 return PGRES_POLLING_FAILED;
1123 /* SSL handshake is complete */
1124 return PGRES_POLLING_OK;
1128 * Close SSL connection.
1131 close_SSL(PGconn *conn)
1135 SSL_shutdown(conn->ssl);
1136 SSL_free(conn->ssl);
1142 X509_free(conn->peer);
1148 * Obtain reason string for last SSL error
1150 * Some caution is needed here since ERR_reason_error_string will
1151 * return NULL if it doesn't recognize the error code. We don't
1152 * want to return NULL ever.
1154 static char ssl_nomem[] = "Out of memory allocating error description";
1156 #define SSL_ERR_LEN 128
1161 unsigned long errcode;
1162 const char *errreason;
1165 errbuf = malloc(SSL_ERR_LEN);
1168 errcode = ERR_get_error();
1171 strcpy(errbuf, "No SSL error reported");
1174 errreason = ERR_reason_error_string(errcode);
1175 if (errreason != NULL)
1177 strncpy(errbuf, errreason, SSL_ERR_LEN - 1);
1178 errbuf[SSL_ERR_LEN - 1] = '\0';
1181 snprintf(errbuf, SSL_ERR_LEN, "SSL error code %lu", errcode);
1186 SSLerrfree(char *buf)
1188 if (buf != ssl_nomem)
1193 * Return pointer to SSL object.
1196 PQgetssl(PGconn *conn)
1202 #endif /* USE_SSL */
1205 #ifdef ENABLE_THREAD_SAFETY
1208 * Check SIGPIPE handler and perhaps install our own.
1211 pq_check_sigpipe_handler(void)
1213 pthread_key_create(&pq_thread_in_send, NULL);
1216 * Find current pipe handler and chain on to it.
1218 pq_pipe_handler = pqsignalinquire(SIGPIPE);
1219 pqsignal(SIGPIPE, sigpipe_handler_ignore_send);
1223 * Threaded SIGPIPE signal handler
1226 sigpipe_handler_ignore_send(int signo)
1229 * If we have gotten a SIGPIPE outside send(), chain or exit if we are
1230 * at the end of the chain. Synchronous signals are delivered to the
1231 * thread that caused the signal.
1235 if (pq_pipe_handler == SIG_DFL) /* not set by application */
1236 exit(128 + SIGPIPE); /* typical return value for SIG_DFL */
1238 (*pq_pipe_handler) (signo); /* call original handler */
1245 * Indicates whether the current thread is in send()
1246 * For use by SIGPIPE signal handlers; they should
1247 * ignore SIGPIPE when libpq is in send(). This means
1248 * that the backend has died unexpectedly.
1253 #ifdef ENABLE_THREAD_SAFETY
1254 return (pthread_getspecific(pq_thread_in_send) /* has it been set? */ &&
1255 *(char *) pthread_getspecific(pq_thread_in_send) == 't') ? true : false;
1259 * No threading: our code ignores SIGPIPE around send(). Therefore, we
1260 * can't be in send() if we are checking from a SIGPIPE signal