]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-secure.c
Fix another passel of include-file breakage. Kris Jurka, Tom Lane
[postgresql] / src / interfaces / libpq / fe-secure.c
1 /*-------------------------------------------------------------------------
2  *
3  * fe-secure.c
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.
7  *
8  *
9  * Portions Copyright (c) 1996-2006, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        $PostgreSQL: pgsql/src/interfaces/libpq/fe-secure.c,v 1.85 2006/07/14 16:59:19 tgl Exp $
15  *
16  * NOTES
17  *        [ Most of these notes are wrong/obsolete, but perhaps not all ]
18  *
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.
24  *
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.
32  *
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.
39  *
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
48  *        a fix.
49  *
50  *        ...
51  *
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.
56  *
57  *        ...
58  *
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.
64  *
65  *        The user's certificate and private key are located in
66  *              ~/.postgresql/postgresql.crt
67  *        and
68  *              ~/.postgresql/postgresql.key
69  *        respectively.
70  *
71  *        ...
72  *
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.
76  *
77  *-------------------------------------------------------------------------
78  */
79
80 #include "postgres_fe.h"
81
82 #include <signal.h>
83 #include <fcntl.h>
84 #include <ctype.h>
85
86 #include "libpq-fe.h"
87 #include "fe-auth.h"
88 #include "pqsignal.h"
89
90 #ifdef WIN32
91 #include "win32.h"
92 #else
93 #include <sys/socket.h>
94 #include <unistd.h>
95 #include <netdb.h>
96 #include <netinet/in.h>
97 #ifdef HAVE_NETINET_TCP_H
98 #include <netinet/tcp.h>
99 #endif
100 #include <arpa/inet.h>
101 #endif
102 #include <sys/stat.h>
103
104 #ifdef ENABLE_THREAD_SAFETY
105 #ifdef WIN32
106 #include "pthread-win32.h"
107 #else
108 #include <pthread.h>
109 #endif
110 #endif
111
112 #ifndef HAVE_STRDUP
113 #include "strdup.h"
114 #endif
115
116 #ifdef USE_SSL
117 #include <openssl/ssl.h>
118 #endif   /* USE_SSL */
119
120
121 #ifdef USE_SSL
122
123 #ifndef WIN32
124 #define USER_CERT_FILE          ".postgresql/postgresql.crt"
125 #define USER_KEY_FILE           ".postgresql/postgresql.key"
126 #define ROOT_CERT_FILE          ".postgresql/root.crt"
127 #define ROOT_CRL_FILE           ".postgresql/root.crl"
128 #else
129 /* On Windows, the "home" directory is already PostgreSQL-specific */
130 #define USER_CERT_FILE          "postgresql.crt"
131 #define USER_KEY_FILE           "postgresql.key"
132 #define ROOT_CERT_FILE          "root.crt"
133 #define ROOT_CRL_FILE           "root.crl"
134 #endif
135
136 #ifdef NOT_USED
137 static int      verify_peer(PGconn *);
138 #endif
139 static int      verify_cb(int ok, X509_STORE_CTX *ctx);
140 static int      client_cert_cb(SSL *, X509 **, EVP_PKEY **);
141 static int      init_ssl_system(PGconn *conn);
142 static int      initialize_SSL(PGconn *);
143 static void destroy_SSL(void);
144 static PostgresPollingStatusType open_client_SSL(PGconn *);
145 static void close_SSL(PGconn *);
146 static char *SSLerrmessage(void);
147 static void SSLerrfree(char *buf);
148 #endif
149
150 #ifdef USE_SSL
151 static bool pq_initssllib = true;
152
153 static SSL_CTX *SSL_context = NULL;
154 #endif
155
156 /* ------------------------------------------------------------ */
157 /*                       Procedures common to all secure sessions                       */
158 /* ------------------------------------------------------------ */
159
160
161 /*
162  *      Exported function to allow application to tell us it's already
163  *      initialized OpenSSL.
164  */
165 void
166 PQinitSSL(int do_init)
167 {
168 #ifdef USE_SSL
169         pq_initssllib = do_init;
170 #endif
171 }
172
173 /*
174  *      Initialize global context
175  */
176 int
177 pqsecure_initialize(PGconn *conn)
178 {
179         int                     r = 0;
180
181 #ifdef USE_SSL
182         r = initialize_SSL(conn);
183 #endif
184
185         return r;
186 }
187
188 /*
189  *      Destroy global context
190  */
191 void
192 pqsecure_destroy(void)
193 {
194 #ifdef USE_SSL
195         destroy_SSL();
196 #endif
197 }
198
199 /*
200  *      Attempt to negotiate secure session.
201  */
202 PostgresPollingStatusType
203 pqsecure_open_client(PGconn *conn)
204 {
205 #ifdef USE_SSL
206         /* First time through? */
207         if (conn->ssl == NULL)
208         {
209                 if (!(conn->ssl = SSL_new(SSL_context)) ||
210                         !SSL_set_app_data(conn->ssl, conn) ||
211                         !SSL_set_fd(conn->ssl, conn->sock))
212                 {
213                         char       *err = SSLerrmessage();
214
215                         printfPQExpBuffer(&conn->errorMessage,
216                                    libpq_gettext("could not establish SSL connection: %s\n"),
217                                                           err);
218                         SSLerrfree(err);
219                         close_SSL(conn);
220                         return PGRES_POLLING_FAILED;
221                 }
222
223                 /*
224                  * Initialize errorMessage to empty.  This allows open_client_SSL() to
225                  * detect whether client_cert_cb() has stored a message.
226                  */
227                 resetPQExpBuffer(&conn->errorMessage);
228         }
229         /* Begin or continue the actual handshake */
230         return open_client_SSL(conn);
231 #else
232         /* shouldn't get here */
233         return PGRES_POLLING_FAILED;
234 #endif
235 }
236
237 /*
238  *      Close secure session.
239  */
240 void
241 pqsecure_close(PGconn *conn)
242 {
243 #ifdef USE_SSL
244         if (conn->ssl)
245                 close_SSL(conn);
246 #endif
247 }
248
249 /*
250  *      Read data from a secure connection.
251  */
252 ssize_t
253 pqsecure_read(PGconn *conn, void *ptr, size_t len)
254 {
255         ssize_t         n;
256
257 #ifdef USE_SSL
258         if (conn->ssl)
259         {
260                 int                     err;
261
262 rloop:
263                 n = SSL_read(conn->ssl, ptr, len);
264                 err = SSL_get_error(conn->ssl, n);
265                 switch (err)
266                 {
267                         case SSL_ERROR_NONE:
268                                 break;
269                         case SSL_ERROR_WANT_READ:
270                                 n = 0;
271                                 break;
272                         case SSL_ERROR_WANT_WRITE:
273
274                                 /*
275                                  * Returning 0 here would cause caller to wait for read-ready,
276                                  * which is not correct since what SSL wants is wait for
277                                  * write-ready.  The former could get us stuck in an infinite
278                                  * wait, so don't risk it; busy-loop instead.
279                                  */
280                                 goto rloop;
281                         case SSL_ERROR_SYSCALL:
282                                 {
283                                         char            sebuf[256];
284
285                                         if (n == -1)
286                                                 printfPQExpBuffer(&conn->errorMessage,
287                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
288                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
289                                         else
290                                         {
291                                                 printfPQExpBuffer(&conn->errorMessage,
292                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
293
294                                                 SOCK_ERRNO_SET(ECONNRESET);
295                                                 n = -1;
296                                         }
297                                         break;
298                                 }
299                         case SSL_ERROR_SSL:
300                                 {
301                                         char       *err = SSLerrmessage();
302
303                                         printfPQExpBuffer(&conn->errorMessage,
304                                                                           libpq_gettext("SSL error: %s\n"), err);
305                                         SSLerrfree(err);
306                                 }
307                                 /* fall through */
308                         case SSL_ERROR_ZERO_RETURN:
309                                 SOCK_ERRNO_SET(ECONNRESET);
310                                 n = -1;
311                                 break;
312                         default:
313                                 printfPQExpBuffer(&conn->errorMessage,
314                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
315                                                                   err);
316                                 n = -1;
317                                 break;
318                 }
319         }
320         else
321 #endif
322                 n = recv(conn->sock, ptr, len, 0);
323
324         return n;
325 }
326
327 /*
328  *      Write data to a secure connection.
329  */
330 ssize_t
331 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
332 {
333         ssize_t         n;
334
335 #ifndef WIN32
336 #ifdef ENABLE_THREAD_SAFETY
337         sigset_t        osigmask;
338         bool            sigpipe_pending;
339         bool            got_epipe = false;
340
341
342         if (pq_block_sigpipe(&osigmask, &sigpipe_pending) < 0)
343                 return -1;
344 #else
345         pqsigfunc       oldsighandler = pqsignal(SIGPIPE, SIG_IGN);
346 #endif   /* ENABLE_THREAD_SAFETY */
347 #endif   /* WIN32 */
348
349 #ifdef USE_SSL
350         if (conn->ssl)
351         {
352                 int                     err;
353
354                 n = SSL_write(conn->ssl, ptr, len);
355                 err = SSL_get_error(conn->ssl, n);
356                 switch (err)
357                 {
358                         case SSL_ERROR_NONE:
359                                 break;
360                         case SSL_ERROR_WANT_READ:
361
362                                 /*
363                                  * Returning 0 here causes caller to wait for write-ready,
364                                  * which is not really the right thing, but it's the best we
365                                  * can do.
366                                  */
367                                 n = 0;
368                                 break;
369                         case SSL_ERROR_WANT_WRITE:
370                                 n = 0;
371                                 break;
372                         case SSL_ERROR_SYSCALL:
373                                 {
374                                         char            sebuf[256];
375
376                                         if (n == -1)
377                                         {
378 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
379                                                 if (SOCK_ERRNO == EPIPE)
380                                                         got_epipe = true;
381 #endif
382                                                 printfPQExpBuffer(&conn->errorMessage,
383                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
384                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
385                                         }
386                                         else
387                                         {
388                                                 printfPQExpBuffer(&conn->errorMessage,
389                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
390                                                 SOCK_ERRNO_SET(ECONNRESET);
391                                                 n = -1;
392                                         }
393                                         break;
394                                 }
395                         case SSL_ERROR_SSL:
396                                 {
397                                         char       *err = SSLerrmessage();
398
399                                         printfPQExpBuffer(&conn->errorMessage,
400                                                                           libpq_gettext("SSL error: %s\n"), err);
401                                         SSLerrfree(err);
402                                 }
403                                 /* fall through */
404                         case SSL_ERROR_ZERO_RETURN:
405                                 SOCK_ERRNO_SET(ECONNRESET);
406                                 n = -1;
407                                 break;
408                         default:
409                                 printfPQExpBuffer(&conn->errorMessage,
410                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
411                                                                   err);
412                                 n = -1;
413                                 break;
414                 }
415         }
416         else
417 #endif
418         {
419                 n = send(conn->sock, ptr, len, 0);
420 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
421                 if (n < 0 && SOCK_ERRNO == EPIPE)
422                         got_epipe = true;
423 #endif
424         }
425
426 #ifndef WIN32
427 #ifdef ENABLE_THREAD_SAFETY
428         pq_reset_sigpipe(&osigmask, sigpipe_pending, got_epipe);
429 #else
430         pqsignal(SIGPIPE, oldsighandler);
431 #endif   /* ENABLE_THREAD_SAFETY */
432 #endif   /* WIN32 */
433
434         return n;
435 }
436
437 /* ------------------------------------------------------------ */
438 /*                                                SSL specific code                                             */
439 /* ------------------------------------------------------------ */
440 #ifdef USE_SSL
441
442 /*
443  *      Certificate verification callback
444  *
445  *      This callback allows us to log intermediate problems during
446  *      verification, but there doesn't seem to be a clean way to get
447  *      our PGconn * structure.  So we can't log anything!
448  *
449  *      This callback also allows us to override the default acceptance
450  *      criteria (e.g., accepting self-signed or expired certs), but
451  *      for now we accept the default checks.
452  */
453 static int
454 verify_cb(int ok, X509_STORE_CTX *ctx)
455 {
456         return ok;
457 }
458
459 #ifdef NOT_USED
460 /*
461  *      Verify that common name resolves to peer.
462  */
463 static int
464 verify_peer(PGconn *conn)
465 {
466         struct hostent *h = NULL;
467         struct sockaddr addr;
468         struct sockaddr_in *sin;
469         ACCEPT_TYPE_ARG3 len;
470         char      **s;
471         unsigned long l;
472
473         /* get the address on the other side of the socket */
474         len = sizeof(addr);
475         if (getpeername(conn->sock, &addr, &len) == -1)
476         {
477                 char            sebuf[256];
478
479                 printfPQExpBuffer(&conn->errorMessage,
480                                                   libpq_gettext("error querying socket: %s\n"),
481                                                   SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
482                 return -1;
483         }
484
485         /* weird, but legal case */
486         if (addr.sa_family == AF_UNIX)
487                 return 0;
488
489         {
490                 struct hostent hpstr;
491                 char            buf[BUFSIZ];
492                 int                     herrno = 0;
493
494                 /*
495                  * Currently, pqGethostbyname() is used only on platforms that don't
496                  * have getaddrinfo().  If you enable this function, you should
497                  * convert the pqGethostbyname() function call to use getaddrinfo().
498                  */
499                 pqGethostbyname(conn->peer_cn, &hpstr, buf, sizeof(buf),
500                                                 &h, &herrno);
501         }
502
503         /* what do we know about the peer's common name? */
504         if (h == NULL)
505         {
506                 printfPQExpBuffer(&conn->errorMessage,
507                   libpq_gettext("could not get information about host \"%s\": %s\n"),
508                                                   conn->peer_cn, hstrerror(h_errno));
509                 return -1;
510         }
511
512         /* does the address match? */
513         switch (addr.sa_family)
514         {
515                 case AF_INET:
516                         sin = (struct sockaddr_in *) & addr;
517                         for (s = h->h_addr_list; *s != NULL; s++)
518                         {
519                                 if (!memcmp(&sin->sin_addr.s_addr, *s, h->h_length))
520                                         return 0;
521                         }
522                         break;
523
524                 default:
525                         printfPQExpBuffer(&conn->errorMessage,
526                                                           libpq_gettext("unsupported protocol\n"));
527                         return -1;
528         }
529
530         /*
531          * the prior test should be definitive, but in practice it sometimes
532          * fails.  So we also check the aliases.
533          */
534         for (s = h->h_aliases; *s != NULL; s++)
535         {
536                 if (pg_strcasecmp(conn->peer_cn, *s) == 0)
537                         return 0;
538         }
539
540         /* generate protocol-aware error message */
541         switch (addr.sa_family)
542         {
543                 case AF_INET:
544                         sin = (struct sockaddr_in *) & addr;
545                         l = ntohl(sin->sin_addr.s_addr);
546                         printfPQExpBuffer(&conn->errorMessage,
547                                                           libpq_gettext(
548                                                                                         "server common name \"%s\" does not resolve to %ld.%ld.%ld.%ld\n"),
549                                                  conn->peer_cn, (l >> 24) % 0x100, (l >> 16) % 0x100,
550                                                           (l >> 8) % 0x100, l % 0x100);
551                         break;
552                 default:
553                         printfPQExpBuffer(&conn->errorMessage,
554                                                           libpq_gettext(
555                          "server common name \"%s\" does not resolve to peer address\n"),
556                                                           conn->peer_cn);
557         }
558
559         return -1;
560 }
561 #endif   /* NOT_USED */
562
563 /*
564  *      Callback used by SSL to load client cert and key.
565  *      This callback is only called when the server wants a
566  *      client cert.
567  *
568  *      Must return 1 on success, 0 on no data or error.
569  */
570 static int
571 client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
572 {
573         char            homedir[MAXPGPATH];
574         struct stat buf;
575
576 #ifndef WIN32
577         struct stat buf2;
578 #endif
579         char            fnbuf[MAXPGPATH];
580         FILE       *fp;
581         PGconn     *conn = (PGconn *) SSL_get_app_data(ssl);
582         int                     (*cb) () = NULL;        /* how to read user password */
583         char            sebuf[256];
584
585         if (!pqGetHomeDirectory(homedir, sizeof(homedir)))
586         {
587                 printfPQExpBuffer(&conn->errorMessage,
588                                                   libpq_gettext("could not get user information\n"));
589                 return 0;
590         }
591
592         /* read the user certificate */
593         snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
594         if ((fp = fopen(fnbuf, "r")) == NULL)
595         {
596                 printfPQExpBuffer(&conn->errorMessage,
597                            libpq_gettext("could not open certificate file \"%s\": %s\n"),
598                                                   fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
599                 return 0;
600         }
601         if (PEM_read_X509(fp, x509, NULL, NULL) == NULL)
602         {
603                 char       *err = SSLerrmessage();
604
605                 printfPQExpBuffer(&conn->errorMessage,
606                            libpq_gettext("could not read certificate file \"%s\": %s\n"),
607                                                   fnbuf, err);
608                 SSLerrfree(err);
609                 fclose(fp);
610                 return 0;
611         }
612         fclose(fp);
613
614         /* read the user key */
615         snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
616         if (stat(fnbuf, &buf) == -1)
617         {
618                 printfPQExpBuffer(&conn->errorMessage,
619                                                   libpq_gettext("certificate present, but not private key file \"%s\"\n"),
620                                                   fnbuf);
621                 return 0;
622         }
623 #ifndef WIN32
624         if (!S_ISREG(buf.st_mode) || (buf.st_mode & 0077) ||
625                 buf.st_uid != geteuid())
626         {
627                 printfPQExpBuffer(&conn->errorMessage,
628                         libpq_gettext("private key file \"%s\" has wrong permissions\n"),
629                                                   fnbuf);
630                 return 0;
631         }
632 #endif
633         if ((fp = fopen(fnbuf, "r")) == NULL)
634         {
635                 printfPQExpBuffer(&conn->errorMessage,
636                            libpq_gettext("could not open private key file \"%s\": %s\n"),
637                                                   fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
638                 return 0;
639         }
640 #ifndef WIN32
641         if (fstat(fileno(fp), &buf2) == -1 ||
642                 buf.st_dev != buf2.st_dev || buf.st_ino != buf2.st_ino)
643         {
644                 printfPQExpBuffer(&conn->errorMessage,
645                                                   libpq_gettext("private key file \"%s\" changed during execution\n"), fnbuf);
646                 return 0;
647         }
648 #endif
649         if (PEM_read_PrivateKey(fp, pkey, cb, NULL) == NULL)
650         {
651                 char       *err = SSLerrmessage();
652
653                 printfPQExpBuffer(&conn->errorMessage,
654                            libpq_gettext("could not read private key file \"%s\": %s\n"),
655                                                   fnbuf, err);
656                 SSLerrfree(err);
657                 fclose(fp);
658                 return 0;
659         }
660         fclose(fp);
661
662         /* verify that the cert and key go together */
663         if (!X509_check_private_key(*x509, *pkey))
664         {
665                 char       *err = SSLerrmessage();
666
667                 printfPQExpBuffer(&conn->errorMessage,
668                                                   libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
669                                                   fnbuf, err);
670                 SSLerrfree(err);
671                 return 0;
672         }
673
674         return 1;
675 }
676
677 #ifdef ENABLE_THREAD_SAFETY
678
679 static unsigned long
680 pq_threadidcallback(void)
681 {
682         /*
683          * This is not standards-compliant.  pthread_self() returns pthread_t, and
684          * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
685          * it, so we have to do it.
686          */
687         return (unsigned long) pthread_self();
688 }
689
690 static pthread_mutex_t *pq_lockarray;
691
692 static void
693 pq_lockingcallback(int mode, int n, const char *file, int line)
694 {
695         if (mode & CRYPTO_LOCK)
696                 pthread_mutex_lock(&pq_lockarray[n]);
697         else
698                 pthread_mutex_unlock(&pq_lockarray[n]);
699 }
700 #endif   /* ENABLE_THREAD_SAFETY */
701
702 static int
703 init_ssl_system(PGconn *conn)
704 {
705 #ifdef ENABLE_THREAD_SAFETY
706 #ifndef WIN32
707         static pthread_mutex_t init_mutex = PTHREAD_MUTEX_INITIALIZER;
708 #else
709         static pthread_mutex_t init_mutex = NULL;
710         static long mutex_initlock = 0;
711
712         if (init_mutex == NULL)
713         {
714                 while (InterlockedExchange(&mutex_initlock, 1) == 1)
715                          /* loop, another thread own the lock */ ;
716                 if (init_mutex == NULL)
717                         pthread_mutex_init(&init_mutex, NULL);
718                 InterlockedExchange(&mutex_initlock, 0);
719         }
720 #endif
721         pthread_mutex_lock(&init_mutex);
722
723         if (pq_initssllib && pq_lockarray == NULL)
724         {
725                 int                     i;
726
727                 CRYPTO_set_id_callback(pq_threadidcallback);
728
729                 pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
730                 if (!pq_lockarray)
731                 {
732                         pthread_mutex_unlock(&init_mutex);
733                         return -1;
734                 }
735                 for (i = 0; i < CRYPTO_num_locks(); i++)
736                         pthread_mutex_init(&pq_lockarray[i], NULL);
737
738                 CRYPTO_set_locking_callback(pq_lockingcallback);
739         }
740 #endif
741         if (!SSL_context)
742         {
743                 if (pq_initssllib)
744                 {
745                         SSL_library_init();
746                         SSL_load_error_strings();
747                 }
748                 SSL_context = SSL_CTX_new(TLSv1_method());
749                 if (!SSL_context)
750                 {
751                         char       *err = SSLerrmessage();
752
753                         printfPQExpBuffer(&conn->errorMessage,
754                                                  libpq_gettext("could not create SSL context: %s\n"),
755                                                           err);
756                         SSLerrfree(err);
757 #ifdef ENABLE_THREAD_SAFETY
758                         pthread_mutex_unlock(&init_mutex);
759 #endif
760                         return -1;
761                 }
762         }
763 #ifdef ENABLE_THREAD_SAFETY
764         pthread_mutex_unlock(&init_mutex);
765 #endif
766         return 0;
767 }
768
769 /*
770  *      Initialize global SSL context.
771  */
772 static int
773 initialize_SSL(PGconn *conn)
774 {
775         struct stat buf;
776         char            homedir[MAXPGPATH];
777         char            fnbuf[MAXPGPATH];
778
779         if (init_ssl_system(conn))
780                 return -1;
781
782         /* Set up to verify server cert, if root.crt is present */
783         if (pqGetHomeDirectory(homedir, sizeof(homedir)))
784         {
785                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
786                 if (stat(fnbuf, &buf) == 0)
787                 {
788                         X509_STORE *cvstore;
789                         
790                         if (!SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL))
791                         {
792                                 char       *err = SSLerrmessage();
793
794                                 printfPQExpBuffer(&conn->errorMessage,
795                                                                   libpq_gettext("could not read root certificate file \"%s\": %s\n"),
796                                                                   fnbuf, err);
797                                 SSLerrfree(err);
798                                 return -1;
799                         }
800
801                         if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
802                         {
803                                 /* setting the flags to check against the complete CRL chain */
804                                 if (X509_STORE_load_locations(cvstore, ROOT_CRL_FILE, NULL) != 0)
805 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
806 #ifdef X509_V_FLAG_CRL_CHECK
807                                    X509_STORE_set_flags(cvstore,
808                                                                 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
809                                 /* if not found, silently ignore;  we do not require CRL */
810 #else
811                                 {
812                                         char       *err = SSLerrmessage();
813         
814                                         printfPQExpBuffer(&conn->errorMessage,
815                                                                           libpq_gettext("Installed SSL library does not support CRL certificates, file \"%s\"\n"),
816                                                                           fnbuf);
817                                         SSLerrfree(err);
818                                         return -1;
819                                 }
820 #endif
821                         }
822         
823                         SSL_CTX_set_verify(SSL_context, SSL_VERIFY_PEER, verify_cb);
824                 }
825         }
826
827         /* set up mechanism to provide client certificate, if available */
828         SSL_CTX_set_client_cert_cb(SSL_context, client_cert_cb);
829
830         return 0;
831 }
832
833 /*
834  *      Destroy global SSL context.
835  */
836 static void
837 destroy_SSL(void)
838 {
839         if (SSL_context)
840         {
841                 SSL_CTX_free(SSL_context);
842                 SSL_context = NULL;
843         }
844 }
845
846 /*
847  *      Attempt to negotiate SSL connection.
848  */
849 static PostgresPollingStatusType
850 open_client_SSL(PGconn *conn)
851 {
852         int                     r;
853
854         r = SSL_connect(conn->ssl);
855         if (r <= 0)
856         {
857                 int                     err = SSL_get_error(conn->ssl, r);
858
859                 switch (err)
860                 {
861                         case SSL_ERROR_WANT_READ:
862                                 return PGRES_POLLING_READING;
863
864                         case SSL_ERROR_WANT_WRITE:
865                                 return PGRES_POLLING_WRITING;
866
867                         case SSL_ERROR_SYSCALL:
868                                 {
869                                         char            sebuf[256];
870
871                                         if (r == -1)
872                                                 printfPQExpBuffer(&conn->errorMessage,
873                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
874                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
875                                         else
876                                                 printfPQExpBuffer(&conn->errorMessage,
877                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
878                                         close_SSL(conn);
879                                         return PGRES_POLLING_FAILED;
880                                 }
881                         case SSL_ERROR_SSL:
882                                 {
883                                         /*
884                                          * If there are problems with the local certificate files,
885                                          * these will be detected by client_cert_cb() which is
886                                          * called from SSL_connect().  We want to return that
887                                          * error message and not the rather unhelpful error that
888                                          * OpenSSL itself returns.      So check to see if an error
889                                          * message was already stored.
890                                          */
891                                         if (conn->errorMessage.len == 0)
892                                         {
893                                                 char       *err = SSLerrmessage();
894
895                                                 printfPQExpBuffer(&conn->errorMessage,
896                                                                                   libpq_gettext("SSL error: %s\n"),
897                                                                                   err);
898                                                 SSLerrfree(err);
899                                         }
900                                         close_SSL(conn);
901                                         return PGRES_POLLING_FAILED;
902                                 }
903
904                         default:
905                                 printfPQExpBuffer(&conn->errorMessage,
906                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
907                                                                   err);
908                                 close_SSL(conn);
909                                 return PGRES_POLLING_FAILED;
910                 }
911         }
912
913         /* check the certificate chain of the server */
914
915 #ifdef NOT_USED
916         /* CLIENT CERTIFICATES NOT REQUIRED  bjm 2002-09-26 */
917
918         /*
919          * this eliminates simple man-in-the-middle attacks and simple
920          * impersonations
921          */
922         r = SSL_get_verify_result(conn->ssl);
923         if (r != X509_V_OK)
924         {
925                 printfPQExpBuffer(&conn->errorMessage,
926                                    libpq_gettext("certificate could not be validated: %s\n"),
927                                                   X509_verify_cert_error_string(r));
928                 close_SSL(conn);
929                 return PGRES_POLLING_FAILED;
930         }
931 #endif
932
933         /* pull out server distinguished and common names */
934         conn->peer = SSL_get_peer_certificate(conn->ssl);
935         if (conn->peer == NULL)
936         {
937                 char       *err = SSLerrmessage();
938
939                 printfPQExpBuffer(&conn->errorMessage,
940                                         libpq_gettext("certificate could not be obtained: %s\n"),
941                                                   err);
942                 SSLerrfree(err);
943                 close_SSL(conn);
944                 return PGRES_POLLING_FAILED;
945         }
946
947         X509_NAME_oneline(X509_get_subject_name(conn->peer),
948                                           conn->peer_dn, sizeof(conn->peer_dn));
949         conn->peer_dn[sizeof(conn->peer_dn) - 1] = '\0';
950
951         X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
952                                                           NID_commonName, conn->peer_cn, SM_USER);
953         conn->peer_cn[SM_USER] = '\0';
954
955         /* verify that the common name resolves to peer */
956
957 #ifdef NOT_USED
958         /* CLIENT CERTIFICATES NOT REQUIRED  bjm 2002-09-26 */
959
960         /*
961          * this is necessary to eliminate man-in-the-middle attacks and
962          * impersonations where the attacker somehow learned the server's private
963          * key
964          */
965         if (verify_peer(conn) == -1)
966         {
967                 close_SSL(conn);
968                 return PGRES_POLLING_FAILED;
969         }
970 #endif
971
972         /* SSL handshake is complete */
973         return PGRES_POLLING_OK;
974 }
975
976 /*
977  *      Close SSL connection.
978  */
979 static void
980 close_SSL(PGconn *conn)
981 {
982         if (conn->ssl)
983         {
984                 SSL_shutdown(conn->ssl);
985                 SSL_free(conn->ssl);
986                 conn->ssl = NULL;
987         }
988
989         if (conn->peer)
990         {
991                 X509_free(conn->peer);
992                 conn->peer = NULL;
993         }
994 }
995
996 /*
997  * Obtain reason string for last SSL error
998  *
999  * Some caution is needed here since ERR_reason_error_string will
1000  * return NULL if it doesn't recognize the error code.  We don't
1001  * want to return NULL ever.
1002  */
1003 static char ssl_nomem[] = "Out of memory allocating error description";
1004
1005 #define SSL_ERR_LEN 128
1006
1007 static char *
1008 SSLerrmessage(void)
1009 {
1010         unsigned long errcode;
1011         const char *errreason;
1012         char       *errbuf;
1013
1014         errbuf = malloc(SSL_ERR_LEN);
1015         if (!errbuf)
1016                 return ssl_nomem;
1017         errcode = ERR_get_error();
1018         if (errcode == 0)
1019         {
1020                 strcpy(errbuf, "No SSL error reported");
1021                 return errbuf;
1022         }
1023         errreason = ERR_reason_error_string(errcode);
1024         if (errreason != NULL)
1025         {
1026                 strncpy(errbuf, errreason, SSL_ERR_LEN - 1);
1027                 errbuf[SSL_ERR_LEN - 1] = '\0';
1028                 return errbuf;
1029         }
1030         snprintf(errbuf, SSL_ERR_LEN, "SSL error code %lu", errcode);
1031         return errbuf;
1032 }
1033
1034 static void
1035 SSLerrfree(char *buf)
1036 {
1037         if (buf != ssl_nomem)
1038                 free(buf);
1039 }
1040
1041 /*
1042  *      Return pointer to OpenSSL object.
1043  */
1044 void *
1045 PQgetssl(PGconn *conn)
1046 {
1047         if (!conn)
1048                 return NULL;
1049         return conn->ssl;
1050 }
1051 #else                                                   /* !USE_SSL */
1052
1053 void *
1054 PQgetssl(PGconn *conn)
1055 {
1056         return NULL;
1057 }
1058 #endif   /* USE_SSL */
1059
1060 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
1061
1062 /*
1063  *      Block SIGPIPE for this thread.  This prevents send()/write() from exiting
1064  *      the application.
1065  */
1066 int
1067 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1068 {
1069         sigset_t        sigpipe_sigset;
1070         sigset_t        sigset;
1071
1072         sigemptyset(&sigpipe_sigset);
1073         sigaddset(&sigpipe_sigset, SIGPIPE);
1074
1075         /* Block SIGPIPE and save previous mask for later reset */
1076         SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
1077         if (SOCK_ERRNO)
1078                 return -1;
1079
1080         /* We can have a pending SIGPIPE only if it was blocked before */
1081         if (sigismember(osigset, SIGPIPE))
1082         {
1083                 /* Is there a pending SIGPIPE? */
1084                 if (sigpending(&sigset) != 0)
1085                         return -1;
1086
1087                 if (sigismember(&sigset, SIGPIPE))
1088                         *sigpipe_pending = true;
1089                 else
1090                         *sigpipe_pending = false;
1091         }
1092         else
1093                 *sigpipe_pending = false;
1094
1095         return 0;
1096 }
1097
1098 /*
1099  *      Discard any pending SIGPIPE and reset the signal mask.
1100  *
1101  * Note: we are effectively assuming here that the C library doesn't queue
1102  * up multiple SIGPIPE events.  If it did, then we'd accidentally leave
1103  * ours in the queue when an event was already pending and we got another.
1104  * As long as it doesn't queue multiple events, we're OK because the caller
1105  * can't tell the difference.
1106  *
1107  * The caller should say got_epipe = FALSE if it is certain that it
1108  * didn't get an EPIPE error; in that case we'll skip the clear operation
1109  * and things are definitely OK, queuing or no.  If it got one or might have
1110  * gotten one, pass got_epipe = TRUE.
1111  *
1112  * We do not want this to change errno, since if it did that could lose
1113  * the error code from a preceding send().      We essentially assume that if
1114  * we were able to do pq_block_sigpipe(), this can't fail.
1115  */
1116 void
1117 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1118 {
1119         int                     save_errno = SOCK_ERRNO;
1120         int                     signo;
1121         sigset_t        sigset;
1122
1123         /* Clear SIGPIPE only if none was pending */
1124         if (got_epipe && !sigpipe_pending)
1125         {
1126                 if (sigpending(&sigset) == 0 &&
1127                         sigismember(&sigset, SIGPIPE))
1128                 {
1129                         sigset_t        sigpipe_sigset;
1130
1131                         sigemptyset(&sigpipe_sigset);
1132                         sigaddset(&sigpipe_sigset, SIGPIPE);
1133
1134                         sigwait(&sigpipe_sigset, &signo);
1135                 }
1136         }
1137
1138         /* Restore saved block mask */
1139         pthread_sigmask(SIG_SETMASK, osigset, NULL);
1140
1141         SOCK_ERRNO_SET(save_errno);
1142 }
1143
1144 #endif   /* ENABLE_THREAD_SAFETY */