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