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