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.53 2004/09/27 23:38:45 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 * "$HOME/.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 ($HOME/.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 * $HOME/.postgresql/postgresql.crt
68 * $HOME/.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.
78 * The code currently assumes a POSIX password entry. How should
79 * Windows and Mac users be handled?
81 *-------------------------------------------------------------------------
84 #include "postgres_fe.h"
86 #include <sys/types.h>
94 #include "libpq-int.h"
101 #include <sys/socket.h>
104 #include <netinet/in.h>
105 #ifdef HAVE_NETINET_TCP_H
106 #include <netinet/tcp.h>
108 #include <arpa/inet.h>
111 #ifdef ENABLE_THREAD_SAFETY
122 #include <sys/stat.h>
125 #include <openssl/ssl.h>
126 #include <openssl/dh.h>
131 static int verify_cb(int ok, X509_STORE_CTX *ctx);
134 static int verify_peer(PGconn *);
136 static DH *load_dh_file(int keylength);
137 static DH *load_dh_buffer(const char *, size_t);
138 static DH *tmp_dh_cb(SSL *s, int is_export, int keylength);
139 static int client_cert_cb(SSL *, X509 **, EVP_PKEY **);
140 static int init_ssl_system(PGconn *conn);
141 static int initialize_SSL(PGconn *);
142 static void destroy_SSL(void);
143 static PostgresPollingStatusType open_client_SSL(PGconn *);
144 static void close_SSL(PGconn *);
145 static char *SSLerrmessage(void);
146 static void SSLerrfree(char *buf);
150 bool pq_initssllib = true;
152 static SSL_CTX *SSL_context = NULL;
155 #ifdef ENABLE_THREAD_SAFETY
156 static void sigpipe_handler_ignore_send(int signo);
157 pthread_key_t pq_thread_in_send = 0; /* initializer needed on Darwin */
158 static pqsigfunc pq_pipe_handler;
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 * $HOME/.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 /* ------------------------------------------------------------ */
222 * Initialize global context
225 pqsecure_initialize(PGconn *conn)
230 r = initialize_SSL(conn);
237 * Destroy global context
240 pqsecure_destroy(void)
248 * Attempt to negotiate secure session.
250 PostgresPollingStatusType
251 pqsecure_open_client(PGconn *conn)
254 /* First time through? */
255 if (conn->ssl == NULL)
257 if (!(conn->ssl = SSL_new(SSL_context)) ||
258 !SSL_set_app_data(conn->ssl, conn) ||
259 !SSL_set_fd(conn->ssl, conn->sock))
261 char *err = SSLerrmessage();
263 printfPQExpBuffer(&conn->errorMessage,
264 libpq_gettext("could not establish SSL connection: %s\n"),
268 return PGRES_POLLING_FAILED;
271 /* Begin or continue the actual handshake */
272 return open_client_SSL(conn);
274 /* shouldn't get here */
275 return PGRES_POLLING_FAILED;
280 * Close secure session.
283 pqsecure_close(PGconn *conn)
292 * Read data from a secure connection.
295 pqsecure_read(PGconn *conn, void *ptr, size_t len)
305 n = SSL_read(conn->ssl, ptr, len);
306 err = SSL_get_error(conn->ssl, n);
311 case SSL_ERROR_WANT_READ:
314 case SSL_ERROR_WANT_WRITE:
317 * Returning 0 here would cause caller to wait for
318 * read-ready, which is not correct since what SSL wants
319 * is wait for write-ready. The former could get us stuck
320 * in an infinite wait, so don't risk it; busy-loop
324 case SSL_ERROR_SYSCALL:
329 printfPQExpBuffer(&conn->errorMessage,
330 libpq_gettext("SSL SYSCALL error: %s\n"),
331 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
334 printfPQExpBuffer(&conn->errorMessage,
335 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
337 SOCK_ERRNO_SET(ECONNRESET);
344 char *err = SSLerrmessage();
346 printfPQExpBuffer(&conn->errorMessage,
347 libpq_gettext("SSL error: %s\n"), err);
351 case SSL_ERROR_ZERO_RETURN:
352 SOCK_ERRNO_SET(ECONNRESET);
356 printfPQExpBuffer(&conn->errorMessage,
357 libpq_gettext("unrecognized SSL error code: %d\n"),
365 n = recv(conn->sock, ptr, len, 0);
371 * Write data to a secure connection.
374 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
378 #ifdef ENABLE_THREAD_SAFETY
379 pthread_setspecific(pq_thread_in_send, "t");
382 pqsigfunc oldsighandler = pqsignal(SIGPIPE, SIG_IGN);
391 n = SSL_write(conn->ssl, ptr, len);
392 err = SSL_get_error(conn->ssl, n);
397 case SSL_ERROR_WANT_READ:
400 * Returning 0 here causes caller to wait for write-ready,
401 * which is not really the right thing, but it's the best
406 case SSL_ERROR_WANT_WRITE:
409 case SSL_ERROR_SYSCALL:
414 printfPQExpBuffer(&conn->errorMessage,
415 libpq_gettext("SSL SYSCALL error: %s\n"),
416 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
419 printfPQExpBuffer(&conn->errorMessage,
420 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
421 SOCK_ERRNO_SET(ECONNRESET);
428 char *err = SSLerrmessage();
430 printfPQExpBuffer(&conn->errorMessage,
431 libpq_gettext("SSL error: %s\n"), err);
435 case SSL_ERROR_ZERO_RETURN:
436 SOCK_ERRNO_SET(ECONNRESET);
440 printfPQExpBuffer(&conn->errorMessage,
441 libpq_gettext("unrecognized SSL error code: %d\n"),
449 n = send(conn->sock, ptr, len, 0);
451 #ifdef ENABLE_THREAD_SAFETY
452 pthread_setspecific(pq_thread_in_send, "f");
455 pqsignal(SIGPIPE, oldsighandler);
462 /* ------------------------------------------------------------ */
463 /* SSL specific code */
464 /* ------------------------------------------------------------ */
467 * Certificate verification callback
469 * This callback allows us to log intermediate problems during
470 * verification, but there doesn't seem to be a clean way to get
471 * our PGconn * structure. So we can't log anything!
473 * This callback also allows us to override the default acceptance
474 * criteria (e.g., accepting self-signed or expired certs), but
475 * for now we accept the default checks.
478 verify_cb(int ok, X509_STORE_CTX *ctx)
485 * Verify that common name resolves to peer.
488 verify_peer(PGconn *conn)
490 struct hostent *h = NULL;
491 struct sockaddr addr;
492 struct sockaddr_in *sin;
497 /* get the address on the other side of the socket */
499 if (getpeername(conn->sock, &addr, &len) == -1)
503 printfPQExpBuffer(&conn->errorMessage,
504 libpq_gettext("error querying socket: %s\n"),
505 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
509 /* weird, but legal case */
510 if (addr.sa_family == AF_UNIX)
514 struct hostent hpstr;
515 char buf[sizeof(struct hostent)];
519 * Currently, pqGethostbyname() is used only on platforms that
520 * don't have getaddrinfo(). If you enable this function, you
521 * should convert the pqGethostbyname() function call to use
524 pqGethostbyname(conn->peer_cn, &hpstr, buf, sizeof(buf),
528 /* what do we know about the peer's common name? */
531 printfPQExpBuffer(&conn->errorMessage,
532 libpq_gettext("could not get information about host \"%s\": %s\n"),
533 conn->peer_cn, hstrerror(h_errno));
537 /* does the address match? */
538 switch (addr.sa_family)
541 sin = (struct sockaddr_in *) & addr;
542 for (s = h->h_addr_list; *s != NULL; s++)
544 if (!memcmp(&sin->sin_addr.s_addr, *s, h->h_length))
550 printfPQExpBuffer(&conn->errorMessage,
551 libpq_gettext("unsupported protocol\n"));
556 * the prior test should be definitive, but in practice it sometimes
557 * fails. So we also check the aliases.
559 for (s = h->h_aliases; *s != NULL; s++)
561 if (pg_strcasecmp(conn->peer_cn, *s) == 0)
565 /* generate protocol-aware error message */
566 switch (addr.sa_family)
569 sin = (struct sockaddr_in *) & addr;
570 l = ntohl(sin->sin_addr.s_addr);
571 printfPQExpBuffer(&conn->errorMessage,
573 "server common name \"%s\" does not resolve to %ld.%ld.%ld.%ld\n"),
574 conn->peer_cn, (l >> 24) % 0x100, (l >> 16) % 0x100,
575 (l >> 8) % 0x100, l % 0x100);
578 printfPQExpBuffer(&conn->errorMessage,
580 "server common name \"%s\" does not resolve to peer address\n"),
589 * Load precomputed DH parameters.
591 * To prevent "downgrade" attacks, we perform a number of checks
592 * to verify that the DBA-generated DH parameters file contains
593 * what we expect it to contain.
596 load_dh_file(int keylength)
601 char pwdbuf[sizeof(struct passwd)];
602 struct passwd pwdstr;
603 struct passwd *pwd = NULL;
605 char fnbuf[MAXPGPATH];
609 if (pqGetpwuid(getuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
612 /* attempt to open file. It's not an error if it doesn't exist. */
613 snprintf(fnbuf, sizeof(fnbuf), "%s/.postgresql/dh%d.pem",
614 pwd->pw_dir, keylength);
616 if ((fp = fopen(fnbuf, "r")) == NULL)
619 /* flock(fileno(fp), LOCK_SH); */
620 dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
621 /* flock(fileno(fp), LOCK_UN); */
624 /* is the prime the correct size? */
625 if (dh != NULL && 8 * DH_size(dh) < keylength)
628 /* make sure the DH parameters are usable */
631 if (DH_check(dh, &codes))
633 if (codes & DH_CHECK_P_NOT_PRIME)
635 if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
636 (codes & DH_CHECK_P_NOT_SAFE_PRIME))
645 * Load hardcoded DH parameters.
647 * To prevent problems if the DH parameters files don't even
648 * exist, we can load DH parameters hardcoded into this file.
651 load_dh_buffer(const char *buffer, size_t len)
656 bio = BIO_new_mem_buf((char *) buffer, len);
659 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
666 * Generate an empheral DH key. Because this can take a long
667 * time to compute, we can use precomputed parameters of the
670 * Since few sites will bother to precompute these parameter
671 * files, we also provide a fallback to the parameters provided
672 * by the OpenSSL project.
674 * These values can be static (once loaded or computed) since
675 * the OpenSSL library can efficiently generate random keys from
676 * the information provided.
679 tmp_dh_cb(SSL *s, int is_export, int keylength)
682 static DH *dh = NULL;
683 static DH *dh512 = NULL;
684 static DH *dh1024 = NULL;
685 static DH *dh2048 = NULL;
686 static DH *dh4096 = NULL;
692 dh512 = load_dh_file(keylength);
694 dh512 = load_dh_buffer(file_dh512, sizeof file_dh512);
700 dh1024 = load_dh_file(keylength);
702 dh1024 = load_dh_buffer(file_dh1024, sizeof file_dh1024);
708 dh2048 = load_dh_file(keylength);
710 dh2048 = load_dh_buffer(file_dh2048, sizeof file_dh2048);
716 dh4096 = load_dh_file(keylength);
718 dh4096 = load_dh_buffer(file_dh4096, sizeof file_dh4096);
724 dh = load_dh_file(keylength);
728 /* this may take a long time, but it may be necessary... */
729 if (r == NULL || 8 * DH_size(r) < keylength)
730 r = DH_generate_parameters(keylength, DH_GENERATOR_2, NULL, NULL);
736 * Callback used by SSL to load client cert and key.
737 * This callback is only called when the server wants a
740 * Must return 1 on success, 0 on no data or error.
743 client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
748 char pwdbuf[sizeof(struct passwd)];
749 struct passwd pwdstr;
750 struct passwd *pwd = NULL;
753 char fnbuf[MAXPGPATH];
755 PGconn *conn = (PGconn *) SSL_get_app_data(ssl);
756 int (*cb) () = NULL; /* how to read user password */
760 if (pqGetpwuid(getuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
762 printfPQExpBuffer(&conn->errorMessage,
763 libpq_gettext("could not get user information\n"));
767 /* read the user certificate */
768 snprintf(fnbuf, sizeof(fnbuf), "%s/.postgresql/postgresql.crt",
770 if (stat(fnbuf, &buf) == -1)
772 if ((fp = fopen(fnbuf, "r")) == NULL)
774 printfPQExpBuffer(&conn->errorMessage,
775 libpq_gettext("could not open certificate file \"%s\": %s\n"),
776 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
779 if (PEM_read_X509(fp, x509, NULL, NULL) == NULL)
781 char *err = SSLerrmessage();
783 printfPQExpBuffer(&conn->errorMessage,
784 libpq_gettext("could not read certificate file \"%s\": %s\n"),
792 /* read the user key */
793 snprintf(fnbuf, sizeof(fnbuf), "%s/.postgresql/postgresql.key",
795 if (stat(fnbuf, &buf) == -1)
797 printfPQExpBuffer(&conn->errorMessage,
798 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
803 if (!S_ISREG(buf.st_mode) || (buf.st_mode & 0077) ||
804 buf.st_uid != getuid())
806 printfPQExpBuffer(&conn->errorMessage,
807 libpq_gettext("private key file \"%s\" has wrong permissions\n"),
812 if ((fp = fopen(fnbuf, "r")) == NULL)
814 printfPQExpBuffer(&conn->errorMessage,
815 libpq_gettext("could not open private key file \"%s\": %s\n"),
816 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
820 if (fstat(fileno(fp), &buf2) == -1 ||
821 buf.st_dev != buf2.st_dev || buf.st_ino != buf2.st_ino)
823 printfPQExpBuffer(&conn->errorMessage,
824 libpq_gettext("private key file \"%s\" changed during execution\n"), fnbuf);
828 if (PEM_read_PrivateKey(fp, pkey, cb, NULL) == NULL)
830 char *err = SSLerrmessage();
832 printfPQExpBuffer(&conn->errorMessage,
833 libpq_gettext("could not read private key file \"%s\": %s\n"),
842 /* verify that the cert and key go together */
843 if (!X509_check_private_key(*x509, *pkey))
845 char *err = SSLerrmessage();
847 printfPQExpBuffer(&conn->errorMessage,
848 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
852 EVP_PKEY_free(*pkey);
860 #ifdef ENABLE_THREAD_SAFETY
863 pq_threadidcallback(void)
865 return (unsigned long) pthread_self();
868 static pthread_mutex_t *pq_lockarray;
870 pq_lockingcallback(int mode, int n, const char *file, int line)
872 if (mode & CRYPTO_LOCK)
873 pthread_mutex_lock(&pq_lockarray[n]);
875 pthread_mutex_unlock(&pq_lockarray[n]);
877 #endif /* ENABLE_THREAD_SAFETY */
880 init_ssl_system(PGconn *conn)
882 #ifdef ENABLE_THREAD_SAFETY
884 static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
887 static pthread_mutex_t init_mutex = NULL;
888 static long mutex_initlock = 0;
890 if (init_mutex == NULL)
892 while (InterlockedExchange(&mutex_initlock, 1) == 1)
893 /* loop, another thread own the lock */ ;
894 if (init_mutex == NULL)
895 pthread_mutex_init(&init_mutex, NULL);
896 InterlockedExchange(&mutex_initlock, 0);
899 pthread_mutex_lock(&init_mutex);
901 if (pq_initssllib && pq_lockarray == NULL)
905 CRYPTO_set_id_callback(pq_threadidcallback);
907 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
910 pthread_mutex_unlock(&init_mutex);
913 for (i = 0; i < CRYPTO_num_locks(); i++)
914 pthread_mutex_init(&pq_lockarray[i], NULL);
916 CRYPTO_set_locking_callback(pq_lockingcallback);
924 SSL_load_error_strings();
926 SSL_context = SSL_CTX_new(TLSv1_method());
929 char *err = SSLerrmessage();
931 printfPQExpBuffer(&conn->errorMessage,
932 libpq_gettext("could not create SSL context: %s\n"),
935 #ifdef ENABLE_THREAD_SAFETY
936 pthread_mutex_unlock(&init_mutex);
941 #ifdef ENABLE_THREAD_SAFETY
942 pthread_mutex_unlock(&init_mutex);
948 * Initialize global SSL context.
951 initialize_SSL(PGconn *conn)
955 char pwdbuf[sizeof(struct passwd)];
956 struct passwd pwdstr;
957 struct passwd *pwd = NULL;
958 char fnbuf[MAXPGPATH];
961 if (init_ssl_system(conn))
965 /* Set up to verify server cert, if root.crt is present */
966 if (pqGetpwuid(getuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) == 0)
968 snprintf(fnbuf, sizeof(fnbuf), "%s/.postgresql/root.crt",
970 if (stat(fnbuf, &buf) == 0)
972 if (!SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL))
974 char *err = SSLerrmessage();
976 printfPQExpBuffer(&conn->errorMessage,
977 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
983 SSL_CTX_set_verify(SSL_context, SSL_VERIFY_PEER, verify_cb);
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);
1026 case SSL_ERROR_WANT_READ:
1027 return PGRES_POLLING_READING;
1029 case SSL_ERROR_WANT_WRITE:
1030 return PGRES_POLLING_WRITING;
1032 case SSL_ERROR_SYSCALL:
1037 printfPQExpBuffer(&conn->errorMessage,
1038 libpq_gettext("SSL SYSCALL error: %s\n"),
1039 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1041 printfPQExpBuffer(&conn->errorMessage,
1042 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1044 return PGRES_POLLING_FAILED;
1048 char *err = SSLerrmessage();
1050 printfPQExpBuffer(&conn->errorMessage,
1051 libpq_gettext("SSL error: %s\n"), err);
1054 return PGRES_POLLING_FAILED;
1058 printfPQExpBuffer(&conn->errorMessage,
1059 libpq_gettext("unrecognized SSL error code: %d\n"),
1062 return PGRES_POLLING_FAILED;
1066 /* check the certificate chain of the server */
1069 /* CLIENT CERTIFICATES NOT REQUIRED bjm 2002-09-26 */
1072 * this eliminates simple man-in-the-middle attacks and simple
1075 r = SSL_get_verify_result(conn->ssl);
1078 printfPQExpBuffer(&conn->errorMessage,
1079 libpq_gettext("certificate could not be validated: %s\n"),
1080 X509_verify_cert_error_string(r));
1082 return PGRES_POLLING_FAILED;
1086 /* pull out server distinguished and common names */
1087 conn->peer = SSL_get_peer_certificate(conn->ssl);
1088 if (conn->peer == NULL)
1090 char *err = SSLerrmessage();
1092 printfPQExpBuffer(&conn->errorMessage,
1093 libpq_gettext("certificate could not be obtained: %s\n"),
1097 return PGRES_POLLING_FAILED;
1100 X509_NAME_oneline(X509_get_subject_name(conn->peer),
1101 conn->peer_dn, sizeof(conn->peer_dn));
1102 conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
1104 X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
1105 NID_commonName, conn->peer_cn, SM_USER);
1106 conn->peer_cn[SM_USER] = '\0';
1108 /* verify that the common name resolves to peer */
1111 /* CLIENT CERTIFICATES NOT REQUIRED bjm 2002-09-26 */
1114 * this is necessary to eliminate man-in-the-middle attacks and
1115 * impersonations where the attacker somehow learned the server's
1118 if (verify_peer(conn) == -1)
1121 return PGRES_POLLING_FAILED;
1125 /* SSL handshake is complete */
1126 return PGRES_POLLING_OK;
1130 * Close SSL connection.
1133 close_SSL(PGconn *conn)
1137 SSL_shutdown(conn->ssl);
1138 SSL_free(conn->ssl);
1144 X509_free(conn->peer);
1150 * Obtain reason string for last SSL error
1152 * Some caution is needed here since ERR_reason_error_string will
1153 * return NULL if it doesn't recognize the error code. We don't
1154 * want to return NULL ever.
1156 static char ssl_nomem[] = "Out of memory allocating error description";
1158 #define SSL_ERR_LEN 128
1163 unsigned long errcode;
1164 const char *errreason;
1167 errbuf = malloc(SSL_ERR_LEN);
1170 errcode = ERR_get_error();
1173 strcpy(errbuf, "No SSL error reported");
1176 errreason = ERR_reason_error_string(errcode);
1177 if (errreason != NULL)
1179 strncpy(errbuf, errreason, SSL_ERR_LEN - 1);
1180 errbuf[SSL_ERR_LEN - 1] = '\0';
1183 snprintf(errbuf, SSL_ERR_LEN, "SSL error code %lu", errcode);
1188 SSLerrfree(char *buf)
1190 if (buf != ssl_nomem)
1195 * Return pointer to SSL object.
1198 PQgetssl(PGconn *conn)
1204 #endif /* USE_SSL */
1207 #ifdef ENABLE_THREAD_SAFETY
1210 * Check SIGPIPE handler and perhaps install our own.
1213 pq_check_sigpipe_handler(void)
1215 pthread_key_create(&pq_thread_in_send, NULL);
1218 * Find current pipe handler and chain on to it.
1220 pq_pipe_handler = pqsignalinquire(SIGPIPE);
1221 pqsignal(SIGPIPE, sigpipe_handler_ignore_send);
1225 * Threaded SIGPIPE signal handler
1228 sigpipe_handler_ignore_send(int signo)
1231 * If we have gotten a SIGPIPE outside send(), chain or exit if we are
1232 * at the end of the chain. Synchronous signals are delivered to the
1233 * thread that caused the signal.
1237 if (pq_pipe_handler == SIG_DFL) /* not set by application */
1238 exit(128 + SIGPIPE); /* typical return value for SIG_DFL */
1240 (*pq_pipe_handler) (signo); /* call original handler */
1247 * Indicates whether the current thread is in send()
1248 * For use by SIGPIPE signal handlers; they should
1249 * ignore SIGPIPE when libpq is in send(). This means
1250 * that the backend has died unexpectedly.
1255 #ifdef ENABLE_THREAD_SAFETY
1256 return (pthread_getspecific(pq_thread_in_send) /* has it been set? */ &&
1257 *(char *) pthread_getspecific(pq_thread_in_send) == 't') ? true : false;
1261 * No threading: our code ignores SIGPIPE around send(). Therefore, we
1262 * can't be in send() if we are checking from a SIGPIPE signal