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-2005, 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.62 2005/01/04 23:18:25 tgl 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 static bool pq_initssllib = true;
152 static SSL_CTX *SSL_context = NULL;
155 /* ------------------------------------------------------------ */
156 /* Hardcoded values */
157 /* ------------------------------------------------------------ */
160 * Hardcoded DH parameters, used in empheral DH keying.
161 * As discussed above, EDH protects the confidentiality of
162 * sessions even if the static private key is compromised,
163 * so we are *highly* motivated to ensure that we can use
164 * EDH even if the user... or an attacker... deletes the
165 * $HOME/.postgresql/dh*.pem files.
167 * It's not critical that users have EPH keys, but it doesn't
168 * hurt and if it's missing someone will demand it, so....
172 static const char file_dh512[] =
173 "-----BEGIN DH PARAMETERS-----\n\
174 MEYCQQD1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6ypUM2Zafq9AKUJsCRtMIPWak\n\
175 XUGfnHy9iUsiGSa6q6Jew1XpKgVfAgEC\n\
176 -----END DH PARAMETERS-----\n";
178 static const char file_dh1024[] =
179 "-----BEGIN DH PARAMETERS-----\n\
180 MIGHAoGBAPSI/VhOSdvNILSd5JEHNmszbDgNRR0PfIizHHxbLY7288kjwEPwpVsY\n\
181 jY67VYy4XTjTNP18F1dDox0YbN4zISy1Kv884bEpQBgRjXyEpwpy1obEAxnIByl6\n\
182 ypUM2Zafq9AKUJsCRtMIPWakXUGfnHy9iUsiGSa6q6Jew1XpL3jHAgEC\n\
183 -----END DH PARAMETERS-----\n";
185 static const char file_dh2048[] =
186 "-----BEGIN DH PARAMETERS-----\n\
187 MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
188 89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
189 T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
190 zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
191 Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
192 CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
193 -----END DH PARAMETERS-----\n";
195 static const char file_dh4096[] =
196 "-----BEGIN DH PARAMETERS-----\n\
197 MIICCAKCAgEA+hRyUsFN4VpJ1O8JLcCo/VWr19k3BCgJ4uk+d+KhehjdRqNDNyOQ\n\
198 l/MOyQNQfWXPeGKmOmIig6Ev/nm6Nf9Z2B1h3R4hExf+zTiHnvVPeRBhjdQi81rt\n\
199 Xeoh6TNrSBIKIHfUJWBh3va0TxxjQIs6IZOLeVNRLMqzeylWqMf49HsIXqbcokUS\n\
200 Vt1BkvLdW48j8PPv5DsKRN3tloTxqDJGo9tKvj1Fuk74A+Xda1kNhB7KFlqMyN98\n\
201 VETEJ6c7KpfOo30mnK30wqw3S8OtaIR/maYX72tGOno2ehFDkq3pnPtEbD2CScxc\n\
202 alJC+EL7RPk5c/tgeTvCngvc1KZn92Y//EI7G9tPZtylj2b56sHtMftIoYJ9+ODM\n\
203 sccD5Piz/rejE3Ome8EOOceUSCYAhXn8b3qvxVI1ddd1pED6FHRhFvLrZxFvBEM9\n\
204 ERRMp5QqOaHJkM+Dxv8Cj6MqrCbfC4u+ZErxodzuusgDgvZiLF22uxMZbobFWyte\n\
205 OvOzKGtwcTqO/1wV5gKkzu1ZVswVUQd5Gg8lJicwqRWyyNRczDDoG9jVDxmogKTH\n\
206 AaqLulO7R8Ifa1SwF2DteSGVtgWEN8gDpN3RBmmPTDngyF2DHb5qmpnznwtFKdTL\n\
207 KWbuHn491xNO25CQWMtem80uKw+pTnisBRF/454n1Jnhub144YRBoN8CAQI=\n\
208 -----END DH PARAMETERS-----\n";
211 /* ------------------------------------------------------------ */
212 /* Procedures common to all secure sessions */
213 /* ------------------------------------------------------------ */
217 * Exported (but as yet undocumented) function to allow application to
218 * tell us it's already initialized OpenSSL.
221 PQinitSSL(int do_init)
224 pq_initssllib = do_init;
229 * Initialize global context
232 pqsecure_initialize(PGconn *conn)
237 r = initialize_SSL(conn);
244 * Destroy global context
247 pqsecure_destroy(void)
255 * Attempt to negotiate secure session.
257 PostgresPollingStatusType
258 pqsecure_open_client(PGconn *conn)
261 /* First time through? */
262 if (conn->ssl == NULL)
264 if (!(conn->ssl = SSL_new(SSL_context)) ||
265 !SSL_set_app_data(conn->ssl, conn) ||
266 !SSL_set_fd(conn->ssl, conn->sock))
268 char *err = SSLerrmessage();
270 printfPQExpBuffer(&conn->errorMessage,
271 libpq_gettext("could not establish SSL connection: %s\n"),
275 return PGRES_POLLING_FAILED;
278 * Initialize errorMessage to empty. This allows open_client_SSL()
279 * to detect whether client_cert_cb() has stored a message.
281 resetPQExpBuffer(&conn->errorMessage);
283 /* Begin or continue the actual handshake */
284 return open_client_SSL(conn);
286 /* shouldn't get here */
287 return PGRES_POLLING_FAILED;
292 * Close secure session.
295 pqsecure_close(PGconn *conn)
304 * Read data from a secure connection.
307 pqsecure_read(PGconn *conn, void *ptr, size_t len)
317 n = SSL_read(conn->ssl, ptr, len);
318 err = SSL_get_error(conn->ssl, n);
323 case SSL_ERROR_WANT_READ:
326 case SSL_ERROR_WANT_WRITE:
329 * Returning 0 here would cause caller to wait for
330 * read-ready, which is not correct since what SSL wants
331 * is wait for write-ready. The former could get us stuck
332 * in an infinite wait, so don't risk it; busy-loop
336 case SSL_ERROR_SYSCALL:
341 printfPQExpBuffer(&conn->errorMessage,
342 libpq_gettext("SSL SYSCALL error: %s\n"),
343 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
346 printfPQExpBuffer(&conn->errorMessage,
347 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
349 SOCK_ERRNO_SET(ECONNRESET);
356 char *err = SSLerrmessage();
358 printfPQExpBuffer(&conn->errorMessage,
359 libpq_gettext("SSL error: %s\n"), err);
363 case SSL_ERROR_ZERO_RETURN:
364 SOCK_ERRNO_SET(ECONNRESET);
368 printfPQExpBuffer(&conn->errorMessage,
369 libpq_gettext("unrecognized SSL error code: %d\n"),
377 n = recv(conn->sock, ptr, len, 0);
383 * Write data to a secure connection.
386 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
390 #ifdef ENABLE_THREAD_SAFETY
392 bool sigpipe_pending;
393 bool got_epipe = false;
395 if (pq_block_sigpipe(&osigmask, &sigpipe_pending) < 0)
399 pqsigfunc oldsighandler = pqsignal(SIGPIPE, SIG_IGN);
408 n = SSL_write(conn->ssl, ptr, len);
409 err = SSL_get_error(conn->ssl, n);
414 case SSL_ERROR_WANT_READ:
417 * Returning 0 here causes caller to wait for write-ready,
418 * which is not really the right thing, but it's the best
423 case SSL_ERROR_WANT_WRITE:
426 case SSL_ERROR_SYSCALL:
432 #ifdef ENABLE_THREAD_SAFETY
433 if (SOCK_ERRNO == EPIPE)
436 printfPQExpBuffer(&conn->errorMessage,
437 libpq_gettext("SSL SYSCALL error: %s\n"),
438 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
442 printfPQExpBuffer(&conn->errorMessage,
443 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
444 SOCK_ERRNO_SET(ECONNRESET);
451 char *err = SSLerrmessage();
453 printfPQExpBuffer(&conn->errorMessage,
454 libpq_gettext("SSL error: %s\n"), err);
458 case SSL_ERROR_ZERO_RETURN:
459 SOCK_ERRNO_SET(ECONNRESET);
463 printfPQExpBuffer(&conn->errorMessage,
464 libpq_gettext("unrecognized SSL error code: %d\n"),
473 n = send(conn->sock, ptr, len, 0);
474 #ifdef ENABLE_THREAD_SAFETY
475 if (n < 0 && SOCK_ERRNO == EPIPE)
480 #ifdef ENABLE_THREAD_SAFETY
481 pq_reset_sigpipe(&osigmask, sigpipe_pending, got_epipe);
484 pqsignal(SIGPIPE, oldsighandler);
491 /* ------------------------------------------------------------ */
492 /* SSL specific code */
493 /* ------------------------------------------------------------ */
497 * Obtain user's home directory, return in given buffer
499 * This code isn't really SSL-specific, but currently we only need it in
500 * SSL-related places.
503 pqGetHomeDirectory(char *buf, int bufsize)
507 struct passwd pwdstr;
508 struct passwd *pwd = NULL;
510 if (pqGetpwuid(geteuid(), &pwdstr, pwdbuf, sizeof(pwdbuf), &pwd) != 0)
512 StrNCpy(buf, pwd->pw_dir, bufsize);
517 return false; /* PLACEHOLDER */
522 * Certificate verification callback
524 * This callback allows us to log intermediate problems during
525 * verification, but there doesn't seem to be a clean way to get
526 * our PGconn * structure. So we can't log anything!
528 * This callback also allows us to override the default acceptance
529 * criteria (e.g., accepting self-signed or expired certs), but
530 * for now we accept the default checks.
533 verify_cb(int ok, X509_STORE_CTX *ctx)
540 * Verify that common name resolves to peer.
543 verify_peer(PGconn *conn)
545 struct hostent *h = NULL;
546 struct sockaddr addr;
547 struct sockaddr_in *sin;
552 /* get the address on the other side of the socket */
554 if (getpeername(conn->sock, &addr, &len) == -1)
558 printfPQExpBuffer(&conn->errorMessage,
559 libpq_gettext("error querying socket: %s\n"),
560 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
564 /* weird, but legal case */
565 if (addr.sa_family == AF_UNIX)
569 struct hostent hpstr;
574 * Currently, pqGethostbyname() is used only on platforms that
575 * don't have getaddrinfo(). If you enable this function, you
576 * should convert the pqGethostbyname() function call to use
579 pqGethostbyname(conn->peer_cn, &hpstr, buf, sizeof(buf),
583 /* what do we know about the peer's common name? */
586 printfPQExpBuffer(&conn->errorMessage,
587 libpq_gettext("could not get information about host \"%s\": %s\n"),
588 conn->peer_cn, hstrerror(h_errno));
592 /* does the address match? */
593 switch (addr.sa_family)
596 sin = (struct sockaddr_in *) & addr;
597 for (s = h->h_addr_list; *s != NULL; s++)
599 if (!memcmp(&sin->sin_addr.s_addr, *s, h->h_length))
605 printfPQExpBuffer(&conn->errorMessage,
606 libpq_gettext("unsupported protocol\n"));
611 * the prior test should be definitive, but in practice it sometimes
612 * fails. So we also check the aliases.
614 for (s = h->h_aliases; *s != NULL; s++)
616 if (pg_strcasecmp(conn->peer_cn, *s) == 0)
620 /* generate protocol-aware error message */
621 switch (addr.sa_family)
624 sin = (struct sockaddr_in *) & addr;
625 l = ntohl(sin->sin_addr.s_addr);
626 printfPQExpBuffer(&conn->errorMessage,
628 "server common name \"%s\" does not resolve to %ld.%ld.%ld.%ld\n"),
629 conn->peer_cn, (l >> 24) % 0x100, (l >> 16) % 0x100,
630 (l >> 8) % 0x100, l % 0x100);
633 printfPQExpBuffer(&conn->errorMessage,
635 "server common name \"%s\" does not resolve to peer address\n"),
641 #endif /* NOT_USED */
644 * Load precomputed DH parameters.
646 * To prevent "downgrade" attacks, we perform a number of checks
647 * to verify that the DBA-generated DH parameters file contains
648 * what we expect it to contain.
651 load_dh_file(int keylength)
653 char homedir[MAXPGPATH];
654 char fnbuf[MAXPGPATH];
659 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
662 /* attempt to open file. It's not an error if it doesn't exist. */
663 snprintf(fnbuf, sizeof(fnbuf), "%s/.postgresql/dh%d.pem",
666 if ((fp = fopen(fnbuf, "r")) == NULL)
669 /* flock(fileno(fp), LOCK_SH); */
670 dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
671 /* flock(fileno(fp), LOCK_UN); */
674 /* is the prime the correct size? */
675 if (dh != NULL && 8 * DH_size(dh) < keylength)
678 /* make sure the DH parameters are usable */
681 if (DH_check(dh, &codes))
683 if (codes & DH_CHECK_P_NOT_PRIME)
685 if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
686 (codes & DH_CHECK_P_NOT_SAFE_PRIME))
694 * Load hardcoded DH parameters.
696 * To prevent problems if the DH parameters files don't even
697 * exist, we can load DH parameters hardcoded into this file.
700 load_dh_buffer(const char *buffer, size_t len)
705 bio = BIO_new_mem_buf((char *) buffer, len);
708 dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
715 * Generate an empheral DH key. Because this can take a long
716 * time to compute, we can use precomputed parameters of the
719 * Since few sites will bother to precompute these parameter
720 * files, we also provide a fallback to the parameters provided
721 * by the OpenSSL project.
723 * These values can be static (once loaded or computed) since
724 * the OpenSSL library can efficiently generate random keys from
725 * the information provided.
728 tmp_dh_cb(SSL *s, int is_export, int keylength)
731 static DH *dh = NULL;
732 static DH *dh512 = NULL;
733 static DH *dh1024 = NULL;
734 static DH *dh2048 = NULL;
735 static DH *dh4096 = NULL;
741 dh512 = load_dh_file(keylength);
743 dh512 = load_dh_buffer(file_dh512, sizeof file_dh512);
749 dh1024 = load_dh_file(keylength);
751 dh1024 = load_dh_buffer(file_dh1024, sizeof file_dh1024);
757 dh2048 = load_dh_file(keylength);
759 dh2048 = load_dh_buffer(file_dh2048, sizeof file_dh2048);
765 dh4096 = load_dh_file(keylength);
767 dh4096 = load_dh_buffer(file_dh4096, sizeof file_dh4096);
773 dh = load_dh_file(keylength);
777 /* this may take a long time, but it may be necessary... */
778 if (r == NULL || 8 * DH_size(r) < keylength)
779 r = DH_generate_parameters(keylength, DH_GENERATOR_2, NULL, NULL);
785 * Callback used by SSL to load client cert and key.
786 * This callback is only called when the server wants a
789 * Must return 1 on success, 0 on no data or error.
792 client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
794 char homedir[MAXPGPATH];
797 char fnbuf[MAXPGPATH];
799 PGconn *conn = (PGconn *) SSL_get_app_data(ssl);
800 int (*cb) () = NULL; /* how to read user password */
803 if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
805 printfPQExpBuffer(&conn->errorMessage,
806 libpq_gettext("could not get user information\n"));
810 /* read the user certificate */
811 snprintf(fnbuf, sizeof(fnbuf), "%s/.postgresql/postgresql.crt",
813 if ((fp = fopen(fnbuf, "r")) == NULL)
815 printfPQExpBuffer(&conn->errorMessage,
816 libpq_gettext("could not open certificate file \"%s\": %s\n"),
817 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
820 if (PEM_read_X509(fp, x509, NULL, NULL) == NULL)
822 char *err = SSLerrmessage();
824 printfPQExpBuffer(&conn->errorMessage,
825 libpq_gettext("could not read certificate file \"%s\": %s\n"),
833 /* read the user key */
834 snprintf(fnbuf, sizeof(fnbuf), "%s/.postgresql/postgresql.key",
836 if (stat(fnbuf, &buf) == -1)
838 printfPQExpBuffer(&conn->errorMessage,
839 libpq_gettext("certificate present, but not private key file \"%s\"\n"),
843 if (!S_ISREG(buf.st_mode) || (buf.st_mode & 0077) ||
844 buf.st_uid != getuid())
846 printfPQExpBuffer(&conn->errorMessage,
847 libpq_gettext("private key file \"%s\" has wrong permissions\n"),
851 if ((fp = fopen(fnbuf, "r")) == NULL)
853 printfPQExpBuffer(&conn->errorMessage,
854 libpq_gettext("could not open private key file \"%s\": %s\n"),
855 fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
858 if (fstat(fileno(fp), &buf2) == -1 ||
859 buf.st_dev != buf2.st_dev || buf.st_ino != buf2.st_ino)
861 printfPQExpBuffer(&conn->errorMessage,
862 libpq_gettext("private key file \"%s\" changed during execution\n"), fnbuf);
865 if (PEM_read_PrivateKey(fp, pkey, cb, NULL) == NULL)
867 char *err = SSLerrmessage();
869 printfPQExpBuffer(&conn->errorMessage,
870 libpq_gettext("could not read private key file \"%s\": %s\n"),
878 /* verify that the cert and key go together */
879 if (!X509_check_private_key(*x509, *pkey))
881 char *err = SSLerrmessage();
883 printfPQExpBuffer(&conn->errorMessage,
884 libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
893 #ifdef ENABLE_THREAD_SAFETY
896 pq_threadidcallback(void)
898 return (unsigned long) pthread_self();
901 static pthread_mutex_t *pq_lockarray;
904 pq_lockingcallback(int mode, int n, const char *file, int line)
906 if (mode & CRYPTO_LOCK)
907 pthread_mutex_lock(&pq_lockarray[n]);
909 pthread_mutex_unlock(&pq_lockarray[n]);
912 #endif /* ENABLE_THREAD_SAFETY */
915 init_ssl_system(PGconn *conn)
917 #ifdef ENABLE_THREAD_SAFETY
919 static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
922 static pthread_mutex_t init_mutex = NULL;
923 static long mutex_initlock = 0;
925 if (init_mutex == NULL)
927 while (InterlockedExchange(&mutex_initlock, 1) == 1)
928 /* loop, another thread own the lock */ ;
929 if (init_mutex == NULL)
930 pthread_mutex_init(&init_mutex, NULL);
931 InterlockedExchange(&mutex_initlock, 0);
934 pthread_mutex_lock(&init_mutex);
936 if (pq_initssllib && pq_lockarray == NULL)
940 CRYPTO_set_id_callback(pq_threadidcallback);
942 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
945 pthread_mutex_unlock(&init_mutex);
948 for (i = 0; i < CRYPTO_num_locks(); i++)
949 pthread_mutex_init(&pq_lockarray[i], NULL);
951 CRYPTO_set_locking_callback(pq_lockingcallback);
959 SSL_load_error_strings();
961 SSL_context = SSL_CTX_new(TLSv1_method());
964 char *err = SSLerrmessage();
966 printfPQExpBuffer(&conn->errorMessage,
967 libpq_gettext("could not create SSL context: %s\n"),
970 #ifdef ENABLE_THREAD_SAFETY
971 pthread_mutex_unlock(&init_mutex);
976 #ifdef ENABLE_THREAD_SAFETY
977 pthread_mutex_unlock(&init_mutex);
983 * Initialize global SSL context.
986 initialize_SSL(PGconn *conn)
989 char homedir[MAXPGPATH];
990 char fnbuf[MAXPGPATH];
992 if (init_ssl_system(conn))
995 /* Set up to verify server cert, if root.crt is present */
996 if (pqGetHomeDirectory(homedir, sizeof(homedir)))
998 snprintf(fnbuf, sizeof(fnbuf), "%s/.postgresql/root.crt", homedir);
999 if (stat(fnbuf, &buf) == 0)
1001 if (!SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL))
1003 char *err = SSLerrmessage();
1005 printfPQExpBuffer(&conn->errorMessage,
1006 libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1012 SSL_CTX_set_verify(SSL_context, SSL_VERIFY_PEER, verify_cb);
1016 /* set up empheral DH keys */
1017 SSL_CTX_set_tmp_dh_callback(SSL_context, tmp_dh_cb);
1018 SSL_CTX_set_options(SSL_context, SSL_OP_SINGLE_DH_USE);
1020 /* set up mechanism to provide client certificate, if available */
1021 SSL_CTX_set_client_cert_cb(SSL_context, client_cert_cb);
1027 * Destroy global SSL context.
1034 SSL_CTX_free(SSL_context);
1040 * Attempt to negotiate SSL connection.
1042 static PostgresPollingStatusType
1043 open_client_SSL(PGconn *conn)
1047 r = SSL_connect(conn->ssl);
1050 int err = SSL_get_error(conn->ssl, r);
1054 case SSL_ERROR_WANT_READ:
1055 return PGRES_POLLING_READING;
1057 case SSL_ERROR_WANT_WRITE:
1058 return PGRES_POLLING_WRITING;
1060 case SSL_ERROR_SYSCALL:
1065 printfPQExpBuffer(&conn->errorMessage,
1066 libpq_gettext("SSL SYSCALL error: %s\n"),
1067 SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1069 printfPQExpBuffer(&conn->errorMessage,
1070 libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1072 return PGRES_POLLING_FAILED;
1077 * If there are problems with the local certificate files,
1078 * these will be detected by client_cert_cb() which is
1079 * called from SSL_connect(). We want to return that
1080 * error message and not the rather unhelpful error that
1081 * OpenSSL itself returns. So check to see if an error
1082 * message was already stored.
1084 if (conn->errorMessage.len == 0)
1086 char *err = SSLerrmessage();
1088 printfPQExpBuffer(&conn->errorMessage,
1089 libpq_gettext("SSL error: %s\n"),
1094 return PGRES_POLLING_FAILED;
1098 printfPQExpBuffer(&conn->errorMessage,
1099 libpq_gettext("unrecognized SSL error code: %d\n"),
1102 return PGRES_POLLING_FAILED;
1106 /* check the certificate chain of the server */
1109 /* CLIENT CERTIFICATES NOT REQUIRED bjm 2002-09-26 */
1112 * this eliminates simple man-in-the-middle attacks and simple
1115 r = SSL_get_verify_result(conn->ssl);
1118 printfPQExpBuffer(&conn->errorMessage,
1119 libpq_gettext("certificate could not be validated: %s\n"),
1120 X509_verify_cert_error_string(r));
1122 return PGRES_POLLING_FAILED;
1126 /* pull out server distinguished and common names */
1127 conn->peer = SSL_get_peer_certificate(conn->ssl);
1128 if (conn->peer == NULL)
1130 char *err = SSLerrmessage();
1132 printfPQExpBuffer(&conn->errorMessage,
1133 libpq_gettext("certificate could not be obtained: %s\n"),
1137 return PGRES_POLLING_FAILED;
1140 X509_NAME_oneline(X509_get_subject_name(conn->peer),
1141 conn->peer_dn, sizeof(conn->peer_dn));
1142 conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
1144 X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
1145 NID_commonName, conn->peer_cn, SM_USER);
1146 conn->peer_cn[SM_USER] = '\0';
1148 /* verify that the common name resolves to peer */
1151 /* CLIENT CERTIFICATES NOT REQUIRED bjm 2002-09-26 */
1154 * this is necessary to eliminate man-in-the-middle attacks and
1155 * impersonations where the attacker somehow learned the server's
1158 if (verify_peer(conn) == -1)
1161 return PGRES_POLLING_FAILED;
1165 /* SSL handshake is complete */
1166 return PGRES_POLLING_OK;
1170 * Close SSL connection.
1173 close_SSL(PGconn *conn)
1177 SSL_shutdown(conn->ssl);
1178 SSL_free(conn->ssl);
1184 X509_free(conn->peer);
1190 * Obtain reason string for last SSL error
1192 * Some caution is needed here since ERR_reason_error_string will
1193 * return NULL if it doesn't recognize the error code. We don't
1194 * want to return NULL ever.
1196 static char ssl_nomem[] = "Out of memory allocating error description";
1198 #define SSL_ERR_LEN 128
1203 unsigned long errcode;
1204 const char *errreason;
1207 errbuf = malloc(SSL_ERR_LEN);
1210 errcode = ERR_get_error();
1213 strcpy(errbuf, "No SSL error reported");
1216 errreason = ERR_reason_error_string(errcode);
1217 if (errreason != NULL)
1219 strncpy(errbuf, errreason, SSL_ERR_LEN - 1);
1220 errbuf[SSL_ERR_LEN - 1] = '\0';
1223 snprintf(errbuf, SSL_ERR_LEN, "SSL error code %lu", errcode);
1228 SSLerrfree(char *buf)
1230 if (buf != ssl_nomem)
1235 * Return pointer to SSL object.
1238 PQgetssl(PGconn *conn)
1245 #else /* !USE_SSL */
1248 PQgetssl(PGconn *conn)
1253 #endif /* USE_SSL */
1255 #ifdef ENABLE_THREAD_SAFETY
1258 * Block SIGPIPE for this thread. This prevents send()/write() from exiting
1262 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1264 sigset_t sigpipe_sigset;
1267 sigemptyset(&sigpipe_sigset);
1268 sigaddset(&sigpipe_sigset, SIGPIPE);
1270 /* Block SIGPIPE and save previous mask for later reset */
1271 SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
1275 /* We can have a pending SIGPIPE only if it was blocked before */
1276 if (sigismember(osigset, SIGPIPE))
1278 /* Is there a pending SIGPIPE? */
1279 if (sigpending(&sigset) != 0)
1282 if (sigismember(&sigset, SIGPIPE))
1283 *sigpipe_pending = true;
1285 *sigpipe_pending = false;
1288 *sigpipe_pending = false;
1294 * Discard any pending SIGPIPE and reset the signal mask.
1296 * Note: we are effectively assuming here that the C library doesn't queue
1297 * up multiple SIGPIPE events. If it did, then we'd accidentally leave
1298 * ours in the queue when an event was already pending and we got another.
1299 * As long as it doesn't queue multiple events, we're OK because the caller
1300 * can't tell the difference.
1302 * The caller should say got_epipe = FALSE if it is certain that it
1303 * didn't get an EPIPE error; in that case we'll skip the clear operation
1304 * and things are definitely OK, queuing or no. If it got one or might have
1305 * gotten one, pass got_epipe = TRUE.
1307 * We do not want this to change errno, since if it did that could lose
1308 * the error code from a preceding send(). We essentially assume that if
1309 * we were able to do pq_block_sigpipe(), this can't fail.
1312 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1314 int save_errno = SOCK_ERRNO;
1318 /* Clear SIGPIPE only if none was pending */
1319 if (got_epipe && !sigpipe_pending)
1321 if (sigpending(&sigset) == 0 &&
1322 sigismember(&sigset, SIGPIPE))
1324 sigset_t sigpipe_sigset;
1326 sigemptyset(&sigpipe_sigset);
1327 sigaddset(&sigpipe_sigset, SIGPIPE);
1329 sigwait(&sigpipe_sigset, &signo);
1333 /* Restore saved block mask */
1334 pthread_sigmask(SIG_SETMASK, osigset, NULL);
1336 SOCK_ERRNO_SET(save_errno);
1339 #endif /* ENABLE_THREAD_SAFETY */