]> granicus.if.org Git - postgresql/blob - src/interfaces/libpq/fe-secure.c
libpq: have PQconnectdbParams() and PQpingParams accept "" as default
[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-2014, PostgreSQL Global Development Group
10  * Portions Copyright (c) 1994, Regents of the University of California
11  *
12  *
13  * IDENTIFICATION
14  *        src/interfaces/libpq/fe-secure.c
15  *
16  * NOTES
17  *
18  *        We don't provide informational callbacks here (like
19  *        info_cb() in be-secure.c), since there's no good mechanism to
20  *        display such information to the user.
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 "libpq-int.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
48 #include <sys/stat.h>
49
50 #ifdef ENABLE_THREAD_SAFETY
51 #ifdef WIN32
52 #include "pthread-win32.h"
53 #else
54 #include <pthread.h>
55 #endif
56 #endif
57
58 #ifdef USE_SSL
59
60 #include <openssl/ssl.h>
61 #if (SSLEAY_VERSION_NUMBER >= 0x00907000L)
62 #include <openssl/conf.h>
63 #endif
64 #ifdef USE_SSL_ENGINE
65 #include <openssl/engine.h>
66 #endif
67
68
69 #ifndef WIN32
70 #define USER_CERT_FILE          ".postgresql/postgresql.crt"
71 #define USER_KEY_FILE           ".postgresql/postgresql.key"
72 #define ROOT_CERT_FILE          ".postgresql/root.crt"
73 #define ROOT_CRL_FILE           ".postgresql/root.crl"
74 #else
75 /* On Windows, the "home" directory is already PostgreSQL-specific */
76 #define USER_CERT_FILE          "postgresql.crt"
77 #define USER_KEY_FILE           "postgresql.key"
78 #define ROOT_CERT_FILE          "root.crt"
79 #define ROOT_CRL_FILE           "root.crl"
80 #endif
81
82 static bool verify_peer_name_matches_certificate(PGconn *);
83 static int      verify_cb(int ok, X509_STORE_CTX *ctx);
84 static int      init_ssl_system(PGconn *conn);
85 static void destroy_ssl_system(void);
86 static int      initialize_SSL(PGconn *conn);
87 static void destroySSL(void);
88 static PostgresPollingStatusType open_client_SSL(PGconn *);
89 static void close_SSL(PGconn *);
90 static char *SSLerrmessage(void);
91 static void SSLerrfree(char *buf);
92
93 static bool pq_init_ssl_lib = true;
94 static bool pq_init_crypto_lib = true;
95
96 /*
97  * SSL_context is currently shared between threads and therefore we need to be
98  * careful to lock around any usage of it when providing thread safety.
99  * ssl_config_mutex is the mutex that we use to protect it.
100  */
101 static SSL_CTX *SSL_context = NULL;
102
103 #ifdef ENABLE_THREAD_SAFETY
104 static long ssl_open_connections = 0;
105
106 #ifndef WIN32
107 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
108 #else
109 static pthread_mutex_t ssl_config_mutex = NULL;
110 static long win32_ssl_create_mutex = 0;
111 #endif
112 #endif   /* ENABLE_THREAD_SAFETY */
113 #endif   /* SSL */
114
115
116 /*
117  * Macros to handle disabling and then restoring the state of SIGPIPE handling.
118  * On Windows, these are all no-ops since there's no SIGPIPEs.
119  */
120
121 #ifndef WIN32
122
123 #define SIGPIPE_MASKED(conn)    ((conn)->sigpipe_so || (conn)->sigpipe_flag)
124
125 #ifdef ENABLE_THREAD_SAFETY
126
127 struct sigpipe_info
128 {
129         sigset_t        oldsigmask;
130         bool            sigpipe_pending;
131         bool            got_epipe;
132 };
133
134 #define DECLARE_SIGPIPE_INFO(spinfo) struct sigpipe_info spinfo
135
136 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
137         do { \
138                 (spinfo).got_epipe = false; \
139                 if (!SIGPIPE_MASKED(conn)) \
140                 { \
141                         if (pq_block_sigpipe(&(spinfo).oldsigmask, \
142                                                                  &(spinfo).sigpipe_pending) < 0) \
143                                 failaction; \
144                 } \
145         } while (0)
146
147 #define REMEMBER_EPIPE(spinfo, cond) \
148         do { \
149                 if (cond) \
150                         (spinfo).got_epipe = true; \
151         } while (0)
152
153 #define RESTORE_SIGPIPE(conn, spinfo) \
154         do { \
155                 if (!SIGPIPE_MASKED(conn)) \
156                         pq_reset_sigpipe(&(spinfo).oldsigmask, (spinfo).sigpipe_pending, \
157                                                          (spinfo).got_epipe); \
158         } while (0)
159 #else                                                   /* !ENABLE_THREAD_SAFETY */
160
161 #define DECLARE_SIGPIPE_INFO(spinfo) pqsigfunc spinfo = NULL
162
163 #define DISABLE_SIGPIPE(conn, spinfo, failaction) \
164         do { \
165                 if (!SIGPIPE_MASKED(conn)) \
166                         spinfo = pqsignal(SIGPIPE, SIG_IGN); \
167         } while (0)
168
169 #define REMEMBER_EPIPE(spinfo, cond)
170
171 #define RESTORE_SIGPIPE(conn, spinfo) \
172         do { \
173                 if (!SIGPIPE_MASKED(conn)) \
174                         pqsignal(SIGPIPE, spinfo); \
175         } while (0)
176 #endif   /* ENABLE_THREAD_SAFETY */
177 #else                                                   /* WIN32 */
178
179 #define DECLARE_SIGPIPE_INFO(spinfo)
180 #define DISABLE_SIGPIPE(conn, spinfo, failaction)
181 #define REMEMBER_EPIPE(spinfo, cond)
182 #define RESTORE_SIGPIPE(conn, spinfo)
183 #endif   /* WIN32 */
184
185 /* ------------------------------------------------------------ */
186 /*                       Procedures common to all secure sessions                       */
187 /* ------------------------------------------------------------ */
188
189
190 /*
191  *      Exported function to allow application to tell us it's already
192  *      initialized OpenSSL.
193  */
194 void
195 PQinitSSL(int do_init)
196 {
197         PQinitOpenSSL(do_init, do_init);
198 }
199
200 /*
201  *      Exported function to allow application to tell us it's already
202  *      initialized OpenSSL and/or libcrypto.
203  */
204 void
205 PQinitOpenSSL(int do_ssl, int do_crypto)
206 {
207 #ifdef USE_SSL
208 #ifdef ENABLE_THREAD_SAFETY
209
210         /*
211          * Disallow changing the flags while we have open connections, else we'd
212          * get completely confused.
213          */
214         if (ssl_open_connections != 0)
215                 return;
216 #endif
217
218         pq_init_ssl_lib = do_ssl;
219         pq_init_crypto_lib = do_crypto;
220 #endif
221 }
222
223 /*
224  *      Initialize global SSL context
225  */
226 int
227 pqsecure_initialize(PGconn *conn)
228 {
229         int                     r = 0;
230
231 #ifdef USE_SSL
232         r = init_ssl_system(conn);
233 #endif
234
235         return r;
236 }
237
238 /*
239  *      Destroy global context
240  */
241 void
242 pqsecure_destroy(void)
243 {
244 #ifdef USE_SSL
245         destroySSL();
246 #endif
247 }
248
249 /*
250  *      Begin or continue negotiating a secure session.
251  */
252 PostgresPollingStatusType
253 pqsecure_open_client(PGconn *conn)
254 {
255 #ifdef USE_SSL
256         /* First time through? */
257         if (conn->ssl == NULL)
258         {
259 #ifdef ENABLE_THREAD_SAFETY
260                 int rc;
261 #endif
262
263                 /* We cannot use MSG_NOSIGNAL to block SIGPIPE when using SSL */
264                 conn->sigpipe_flag = false;
265
266 #ifdef ENABLE_THREAD_SAFETY
267                 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
268                 {
269                         printfPQExpBuffer(&conn->errorMessage,
270                                                           libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
271                         return PGRES_POLLING_FAILED;
272                 }
273 #endif
274                 /* Create a connection-specific SSL object */
275                 if (!(conn->ssl = SSL_new(SSL_context)) ||
276                         !SSL_set_app_data(conn->ssl, conn) ||
277                         !SSL_set_fd(conn->ssl, conn->sock))
278                 {
279                         char       *err = SSLerrmessage();
280
281                         printfPQExpBuffer(&conn->errorMessage,
282                                    libpq_gettext("could not establish SSL connection: %s\n"),
283                                                           err);
284                         SSLerrfree(err);
285 #ifdef ENABLE_THREAD_SAFETY
286                         pthread_mutex_unlock(&ssl_config_mutex);
287 #endif
288                         close_SSL(conn);
289
290                         return PGRES_POLLING_FAILED;
291                 }
292 #ifdef ENABLE_THREAD_SAFETY
293                 pthread_mutex_unlock(&ssl_config_mutex);
294 #endif
295                 /*
296                  * Load client certificate, private key, and trusted CA certs.
297                  */
298                 if (initialize_SSL(conn) != 0)
299                 {
300                         /* initialize_SSL already put a message in conn->errorMessage */
301                         close_SSL(conn);
302                         return PGRES_POLLING_FAILED;
303                 }
304         }
305
306         /* Begin or continue the actual handshake */
307         return open_client_SSL(conn);
308 #else
309         /* shouldn't get here */
310         return PGRES_POLLING_FAILED;
311 #endif
312 }
313
314 /*
315  *      Close secure session.
316  */
317 void
318 pqsecure_close(PGconn *conn)
319 {
320 #ifdef USE_SSL
321         if (conn->ssl)
322                 close_SSL(conn);
323 #endif
324 }
325
326 /*
327  *      Read data from a secure connection.
328  *
329  * On failure, this function is responsible for putting a suitable message
330  * into conn->errorMessage.  The caller must still inspect errno, but only
331  * to determine whether to continue/retry after error.
332  */
333 ssize_t
334 pqsecure_read(PGconn *conn, void *ptr, size_t len)
335 {
336         ssize_t         n;
337         int                     result_errno = 0;
338         char            sebuf[256];
339
340 #ifdef USE_SSL
341         if (conn->ssl)
342         {
343                 int                     err;
344
345                 DECLARE_SIGPIPE_INFO(spinfo);
346
347                 /* SSL_read can write to the socket, so we need to disable SIGPIPE */
348                 DISABLE_SIGPIPE(conn, spinfo, return -1);
349
350 rloop:
351                 SOCK_ERRNO_SET(0);
352                 n = SSL_read(conn->ssl, ptr, len);
353                 err = SSL_get_error(conn->ssl, n);
354                 switch (err)
355                 {
356                         case SSL_ERROR_NONE:
357                                 if (n < 0)
358                                 {
359                                         /* Not supposed to happen, so we don't translate the msg */
360                                         printfPQExpBuffer(&conn->errorMessage,
361                                                                           "SSL_read failed but did not provide error information\n");
362                                         /* assume the connection is broken */
363                                         result_errno = ECONNRESET;
364                                 }
365                                 break;
366                         case SSL_ERROR_WANT_READ:
367                                 n = 0;
368                                 break;
369                         case SSL_ERROR_WANT_WRITE:
370
371                                 /*
372                                  * Returning 0 here would cause caller to wait for read-ready,
373                                  * which is not correct since what SSL wants is wait for
374                                  * write-ready.  The former could get us stuck in an infinite
375                                  * wait, so don't risk it; busy-loop instead.
376                                  */
377                                 goto rloop;
378                         case SSL_ERROR_SYSCALL:
379                                 if (n < 0)
380                                 {
381                                         result_errno = SOCK_ERRNO;
382                                         REMEMBER_EPIPE(spinfo, result_errno == EPIPE);
383                                         if (result_errno == EPIPE ||
384                                                 result_errno == ECONNRESET)
385                                                 printfPQExpBuffer(&conn->errorMessage,
386                                                                                   libpq_gettext(
387                                                                 "server closed the connection unexpectedly\n"
388                                                                                                                 "\tThis probably means the server terminated abnormally\n"
389                                                          "\tbefore or while processing the request.\n"));
390                                         else
391                                                 printfPQExpBuffer(&conn->errorMessage,
392                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
393                                                                                   SOCK_STRERROR(result_errno,
394                                                                                                           sebuf, sizeof(sebuf)));
395                                 }
396                                 else
397                                 {
398                                         printfPQExpBuffer(&conn->errorMessage,
399                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
400                                         /* assume the connection is broken */
401                                         result_errno = ECONNRESET;
402                                         n = -1;
403                                 }
404                                 break;
405                         case SSL_ERROR_SSL:
406                                 {
407                                         char       *errm = SSLerrmessage();
408
409                                         printfPQExpBuffer(&conn->errorMessage,
410                                                                           libpq_gettext("SSL error: %s\n"), errm);
411                                         SSLerrfree(errm);
412                                         /* assume the connection is broken */
413                                         result_errno = ECONNRESET;
414                                         n = -1;
415                                         break;
416                                 }
417                         case SSL_ERROR_ZERO_RETURN:
418
419                                 /*
420                                  * Per OpenSSL documentation, this error code is only returned
421                                  * for a clean connection closure, so we should not report it
422                                  * as a server crash.
423                                  */
424                                 printfPQExpBuffer(&conn->errorMessage,
425                                                                   libpq_gettext("SSL connection has been closed unexpectedly\n"));
426                                 result_errno = ECONNRESET;
427                                 n = -1;
428                                 break;
429                         default:
430                                 printfPQExpBuffer(&conn->errorMessage,
431                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
432                                                                   err);
433                                 /* assume the connection is broken */
434                                 result_errno = ECONNRESET;
435                                 n = -1;
436                                 break;
437                 }
438
439                 RESTORE_SIGPIPE(conn, spinfo);
440         }
441         else
442 #endif   /* USE_SSL */
443         {
444                 n = recv(conn->sock, ptr, len, 0);
445
446                 if (n < 0)
447                 {
448                         result_errno = SOCK_ERRNO;
449
450                         /* Set error message if appropriate */
451                         switch (result_errno)
452                         {
453 #ifdef EAGAIN
454                                 case EAGAIN:
455 #endif
456 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
457                                 case EWOULDBLOCK:
458 #endif
459                                 case EINTR:
460                                         /* no error message, caller is expected to retry */
461                                         break;
462
463 #ifdef ECONNRESET
464                                 case ECONNRESET:
465                                         printfPQExpBuffer(&conn->errorMessage,
466                                                                           libpq_gettext(
467                                                                 "server closed the connection unexpectedly\n"
468                                         "\tThis probably means the server terminated abnormally\n"
469                                                          "\tbefore or while processing the request.\n"));
470                                         break;
471 #endif
472
473                                 default:
474                                         printfPQExpBuffer(&conn->errorMessage,
475                                         libpq_gettext("could not receive data from server: %s\n"),
476                                                                           SOCK_STRERROR(result_errno,
477                                                                                                         sebuf, sizeof(sebuf)));
478                                         break;
479                         }
480                 }
481         }
482
483         /* ensure we return the intended errno to caller */
484         SOCK_ERRNO_SET(result_errno);
485
486         return n;
487 }
488
489 /*
490  *      Write data to a secure connection.
491  *
492  * On failure, this function is responsible for putting a suitable message
493  * into conn->errorMessage.  The caller must still inspect errno, but only
494  * to determine whether to continue/retry after error.
495  */
496 ssize_t
497 pqsecure_write(PGconn *conn, const void *ptr, size_t len)
498 {
499         ssize_t         n;
500         int                     result_errno = 0;
501         char            sebuf[256];
502
503         DECLARE_SIGPIPE_INFO(spinfo);
504
505 #ifdef USE_SSL
506         if (conn->ssl)
507         {
508                 int                     err;
509
510                 DISABLE_SIGPIPE(conn, spinfo, return -1);
511
512                 SOCK_ERRNO_SET(0);
513                 n = SSL_write(conn->ssl, ptr, len);
514                 err = SSL_get_error(conn->ssl, n);
515                 switch (err)
516                 {
517                         case SSL_ERROR_NONE:
518                                 if (n < 0)
519                                 {
520                                         /* Not supposed to happen, so we don't translate the msg */
521                                         printfPQExpBuffer(&conn->errorMessage,
522                                                                           "SSL_write failed but did not provide error information\n");
523                                         /* assume the connection is broken */
524                                         result_errno = ECONNRESET;
525                                 }
526                                 break;
527                         case SSL_ERROR_WANT_READ:
528
529                                 /*
530                                  * Returning 0 here causes caller to wait for write-ready,
531                                  * which is not really the right thing, but it's the best we
532                                  * can do.
533                                  */
534                                 n = 0;
535                                 break;
536                         case SSL_ERROR_WANT_WRITE:
537                                 n = 0;
538                                 break;
539                         case SSL_ERROR_SYSCALL:
540                                 if (n < 0)
541                                 {
542                                         result_errno = SOCK_ERRNO;
543                                         REMEMBER_EPIPE(spinfo, result_errno == EPIPE);
544                                         if (result_errno == EPIPE ||
545                                                 result_errno == ECONNRESET)
546                                                 printfPQExpBuffer(&conn->errorMessage,
547                                                                                   libpq_gettext(
548                                                                 "server closed the connection unexpectedly\n"
549                                                                                                                 "\tThis probably means the server terminated abnormally\n"
550                                                          "\tbefore or while processing the request.\n"));
551                                         else
552                                                 printfPQExpBuffer(&conn->errorMessage,
553                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
554                                                                                   SOCK_STRERROR(result_errno,
555                                                                                                           sebuf, sizeof(sebuf)));
556                                 }
557                                 else
558                                 {
559                                         printfPQExpBuffer(&conn->errorMessage,
560                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
561                                         /* assume the connection is broken */
562                                         result_errno = ECONNRESET;
563                                         n = -1;
564                                 }
565                                 break;
566                         case SSL_ERROR_SSL:
567                                 {
568                                         char       *errm = SSLerrmessage();
569
570                                         printfPQExpBuffer(&conn->errorMessage,
571                                                                           libpq_gettext("SSL error: %s\n"), errm);
572                                         SSLerrfree(errm);
573                                         /* assume the connection is broken */
574                                         result_errno = ECONNRESET;
575                                         n = -1;
576                                         break;
577                                 }
578                         case SSL_ERROR_ZERO_RETURN:
579
580                                 /*
581                                  * Per OpenSSL documentation, this error code is only returned
582                                  * for a clean connection closure, so we should not report it
583                                  * as a server crash.
584                                  */
585                                 printfPQExpBuffer(&conn->errorMessage,
586                                                                   libpq_gettext("SSL connection has been closed unexpectedly\n"));
587                                 result_errno = ECONNRESET;
588                                 n = -1;
589                                 break;
590                         default:
591                                 printfPQExpBuffer(&conn->errorMessage,
592                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
593                                                                   err);
594                                 /* assume the connection is broken */
595                                 result_errno = ECONNRESET;
596                                 n = -1;
597                                 break;
598                 }
599         }
600         else
601 #endif   /* USE_SSL */
602         {
603                 int                     flags = 0;
604
605 #ifdef MSG_NOSIGNAL
606                 if (conn->sigpipe_flag)
607                         flags |= MSG_NOSIGNAL;
608
609 retry_masked:
610 #endif   /* MSG_NOSIGNAL */
611
612                 DISABLE_SIGPIPE(conn, spinfo, return -1);
613
614                 n = send(conn->sock, ptr, len, flags);
615
616                 if (n < 0)
617                 {
618                         result_errno = SOCK_ERRNO;
619
620                         /*
621                          * If we see an EINVAL, it may be because MSG_NOSIGNAL isn't
622                          * available on this machine.  So, clear sigpipe_flag so we don't
623                          * try the flag again, and retry the send().
624                          */
625 #ifdef MSG_NOSIGNAL
626                         if (flags != 0 && result_errno == EINVAL)
627                         {
628                                 conn->sigpipe_flag = false;
629                                 flags = 0;
630                                 goto retry_masked;
631                         }
632 #endif   /* MSG_NOSIGNAL */
633
634                         /* Set error message if appropriate */
635                         switch (result_errno)
636                         {
637 #ifdef EAGAIN
638                                 case EAGAIN:
639 #endif
640 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
641                                 case EWOULDBLOCK:
642 #endif
643                                 case EINTR:
644                                         /* no error message, caller is expected to retry */
645                                         break;
646
647                                 case EPIPE:
648                                         /* Set flag for EPIPE */
649                                         REMEMBER_EPIPE(spinfo, true);
650                                         /* FALL THRU */
651
652 #ifdef ECONNRESET
653                                 case ECONNRESET:
654 #endif
655                                         printfPQExpBuffer(&conn->errorMessage,
656                                                                           libpq_gettext(
657                                                                 "server closed the connection unexpectedly\n"
658                                         "\tThis probably means the server terminated abnormally\n"
659                                                          "\tbefore or while processing the request.\n"));
660                                         break;
661
662                                 default:
663                                         printfPQExpBuffer(&conn->errorMessage,
664                                                 libpq_gettext("could not send data to server: %s\n"),
665                                                                           SOCK_STRERROR(result_errno,
666                                                                                                         sebuf, sizeof(sebuf)));
667                                         break;
668                         }
669                 }
670         }
671
672         RESTORE_SIGPIPE(conn, spinfo);
673
674         /* ensure we return the intended errno to caller */
675         SOCK_ERRNO_SET(result_errno);
676
677         return n;
678 }
679
680 /* ------------------------------------------------------------ */
681 /*                                                SSL specific code                                             */
682 /* ------------------------------------------------------------ */
683 #ifdef USE_SSL
684
685 /*
686  *      Certificate verification callback
687  *
688  *      This callback allows us to log intermediate problems during
689  *      verification, but there doesn't seem to be a clean way to get
690  *      our PGconn * structure.  So we can't log anything!
691  *
692  *      This callback also allows us to override the default acceptance
693  *      criteria (e.g., accepting self-signed or expired certs), but
694  *      for now we accept the default checks.
695  */
696 static int
697 verify_cb(int ok, X509_STORE_CTX *ctx)
698 {
699         return ok;
700 }
701
702
703 /*
704  * Check if a wildcard certificate matches the server hostname.
705  *
706  * The rule for this is:
707  *      1. We only match the '*' character as wildcard
708  *      2. We match only wildcards at the start of the string
709  *      3. The '*' character does *not* match '.', meaning that we match only
710  *         a single pathname component.
711  *      4. We don't support more than one '*' in a single pattern.
712  *
713  * This is roughly in line with RFC2818, but contrary to what most browsers
714  * appear to be implementing (point 3 being the difference)
715  *
716  * Matching is always case-insensitive, since DNS is case insensitive.
717  */
718 static int
719 wildcard_certificate_match(const char *pattern, const char *string)
720 {
721         int                     lenpat = strlen(pattern);
722         int                     lenstr = strlen(string);
723
724         /* If we don't start with a wildcard, it's not a match (rule 1 & 2) */
725         if (lenpat < 3 ||
726                 pattern[0] != '*' ||
727                 pattern[1] != '.')
728                 return 0;
729
730         if (lenpat > lenstr)
731                 /* If pattern is longer than the string, we can never match */
732                 return 0;
733
734         if (pg_strcasecmp(pattern + 1, string + lenstr - lenpat + 1) != 0)
735
736                 /*
737                  * If string does not end in pattern (minus the wildcard), we don't
738                  * match
739                  */
740                 return 0;
741
742         if (strchr(string, '.') < string + lenstr - lenpat)
743
744                 /*
745                  * If there is a dot left of where the pattern started to match, we
746                  * don't match (rule 3)
747                  */
748                 return 0;
749
750         /* String ended with pattern, and didn't have a dot before, so we match */
751         return 1;
752 }
753
754
755 /*
756  *      Verify that common name resolves to peer.
757  */
758 static bool
759 verify_peer_name_matches_certificate(PGconn *conn)
760 {
761         char       *peer_cn;
762         int                     r;
763         int                     len;
764         bool            result;
765
766         /*
767          * If told not to verify the peer name, don't do it. Return true
768          * indicating that the verification was successful.
769          */
770         if (strcmp(conn->sslmode, "verify-full") != 0)
771                 return true;
772
773         /*
774          * Extract the common name from the certificate.
775          *
776          * XXX: Should support alternate names here
777          */
778         /* First find out the name's length and allocate a buffer for it. */
779         len = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
780                                                                         NID_commonName, NULL, 0);
781         if (len == -1)
782         {
783                 printfPQExpBuffer(&conn->errorMessage,
784                                                   libpq_gettext("could not get server common name from server certificate\n"));
785                 return false;
786         }
787         peer_cn = malloc(len + 1);
788         if (peer_cn == NULL)
789         {
790                 printfPQExpBuffer(&conn->errorMessage,
791                                                   libpq_gettext("out of memory\n"));
792                 return false;
793         }
794
795         r = X509_NAME_get_text_by_NID(X509_get_subject_name(conn->peer),
796                                                                   NID_commonName, peer_cn, len + 1);
797         if (r != len)
798         {
799                 /* Got different length than on the first call. Shouldn't happen. */
800                 printfPQExpBuffer(&conn->errorMessage,
801                                                   libpq_gettext("could not get server common name from server certificate\n"));
802                 free(peer_cn);
803                 return false;
804         }
805         peer_cn[len] = '\0';
806
807         /*
808          * Reject embedded NULLs in certificate common name to prevent attacks
809          * like CVE-2009-4034.
810          */
811         if (len != strlen(peer_cn))
812         {
813                 printfPQExpBuffer(&conn->errorMessage,
814                                                   libpq_gettext("SSL certificate's common name contains embedded null\n"));
815                 free(peer_cn);
816                 return false;
817         }
818
819         /*
820          * We got the peer's common name. Now compare it against the originally
821          * given hostname.
822          */
823         if (!(conn->pghost && conn->pghost[0] != '\0'))
824         {
825                 printfPQExpBuffer(&conn->errorMessage,
826                                                   libpq_gettext("host name must be specified for a verified SSL connection\n"));
827                 result = false;
828         }
829         else
830         {
831                 if (pg_strcasecmp(peer_cn, conn->pghost) == 0)
832                         /* Exact name match */
833                         result = true;
834                 else if (wildcard_certificate_match(peer_cn, conn->pghost))
835                         /* Matched wildcard certificate */
836                         result = true;
837                 else
838                 {
839                         printfPQExpBuffer(&conn->errorMessage,
840                                                           libpq_gettext("server common name \"%s\" does not match host name \"%s\"\n"),
841                                                           peer_cn, conn->pghost);
842                         result = false;
843                 }
844         }
845
846         free(peer_cn);
847         return result;
848 }
849
850 #ifdef ENABLE_THREAD_SAFETY
851 /*
852  *      Callback functions for OpenSSL internal locking
853  */
854
855 static unsigned long
856 pq_threadidcallback(void)
857 {
858         /*
859          * This is not standards-compliant.  pthread_self() returns pthread_t, and
860          * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
861          * it, so we have to do it.
862          */
863         return (unsigned long) pthread_self();
864 }
865
866 static pthread_mutex_t *pq_lockarray;
867
868 static void
869 pq_lockingcallback(int mode, int n, const char *file, int line)
870 {
871         if (mode & CRYPTO_LOCK)
872         {
873                 if (pthread_mutex_lock(&pq_lockarray[n]))
874                         PGTHREAD_ERROR("failed to lock mutex");
875         }
876         else
877         {
878                 if (pthread_mutex_unlock(&pq_lockarray[n]))
879                         PGTHREAD_ERROR("failed to unlock mutex");
880         }
881 }
882 #endif   /* ENABLE_THREAD_SAFETY */
883
884 /*
885  * Initialize SSL system, in particular creating the SSL_context object
886  * that will be shared by all SSL-using connections in this process.
887  *
888  * In threadsafe mode, this includes setting up libcrypto callback functions
889  * to do thread locking.
890  *
891  * If the caller has told us (through PQinitOpenSSL) that he's taking care
892  * of libcrypto, we expect that callbacks are already set, and won't try to
893  * override it.
894  *
895  * The conn parameter is only used to be able to pass back an error
896  * message - no connection-local setup is made here.
897  *
898  * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
899  */
900 static int
901 init_ssl_system(PGconn *conn)
902 {
903 #ifdef ENABLE_THREAD_SAFETY
904 #ifdef WIN32
905         /* Also see similar code in fe-connect.c, default_threadlock() */
906         if (ssl_config_mutex == NULL)
907         {
908                 while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
909                          /* loop, another thread own the lock */ ;
910                 if (ssl_config_mutex == NULL)
911                 {
912                         if (pthread_mutex_init(&ssl_config_mutex, NULL))
913                                 return -1;
914                 }
915                 InterlockedExchange(&win32_ssl_create_mutex, 0);
916         }
917 #endif
918         if (pthread_mutex_lock(&ssl_config_mutex))
919                 return -1;
920
921         if (pq_init_crypto_lib)
922         {
923                 /*
924                  * If necessary, set up an array to hold locks for libcrypto.
925                  * libcrypto will tell us how big to make this array.
926                  */
927                 if (pq_lockarray == NULL)
928                 {
929                         int                     i;
930
931                         pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
932                         if (!pq_lockarray)
933                         {
934                                 pthread_mutex_unlock(&ssl_config_mutex);
935                                 return -1;
936                         }
937                         for (i = 0; i < CRYPTO_num_locks(); i++)
938                         {
939                                 if (pthread_mutex_init(&pq_lockarray[i], NULL))
940                                 {
941                                         free(pq_lockarray);
942                                         pq_lockarray = NULL;
943                                         pthread_mutex_unlock(&ssl_config_mutex);
944                                         return -1;
945                                 }
946                         }
947                 }
948
949                 if (ssl_open_connections++ == 0)
950                 {
951                         /* These are only required for threaded libcrypto applications */
952                         CRYPTO_set_id_callback(pq_threadidcallback);
953                         CRYPTO_set_locking_callback(pq_lockingcallback);
954                 }
955         }
956 #endif   /* ENABLE_THREAD_SAFETY */
957
958         if (!SSL_context)
959         {
960                 if (pq_init_ssl_lib)
961                 {
962 #if SSLEAY_VERSION_NUMBER >= 0x00907000L
963                         OPENSSL_config(NULL);
964 #endif
965                         SSL_library_init();
966                         SSL_load_error_strings();
967                 }
968
969                 /*
970                  * We use SSLv23_method() because it can negotiate use of the highest
971                  * mutually supported protocol version, while alternatives like
972                  * TLSv1_2_method() permit only one specific version.  Note that we
973                  * don't actually allow SSL v2 or v3, only TLS protocols (see below).
974                  */
975                 SSL_context = SSL_CTX_new(SSLv23_method());
976                 if (!SSL_context)
977                 {
978                         char       *err = SSLerrmessage();
979
980                         printfPQExpBuffer(&conn->errorMessage,
981                                                  libpq_gettext("could not create SSL context: %s\n"),
982                                                           err);
983                         SSLerrfree(err);
984 #ifdef ENABLE_THREAD_SAFETY
985                         pthread_mutex_unlock(&ssl_config_mutex);
986 #endif
987                         return -1;
988                 }
989
990                 /* Disable old protocol versions */
991                 SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
992
993                 /*
994                  * Disable OpenSSL's moving-write-buffer sanity check, because it
995                  * causes unnecessary failures in nonblocking send cases.
996                  */
997                 SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
998         }
999
1000 #ifdef ENABLE_THREAD_SAFETY
1001         pthread_mutex_unlock(&ssl_config_mutex);
1002 #endif
1003         return 0;
1004 }
1005
1006 /*
1007  *      This function is needed because if the libpq library is unloaded
1008  *      from the application, the callback functions will no longer exist when
1009  *      libcrypto is used by other parts of the system.  For this reason,
1010  *      we unregister the callback functions when the last libpq
1011  *      connection is closed.  (The same would apply for OpenSSL callbacks
1012  *      if we had any.)
1013  *
1014  *      Callbacks are only set when we're compiled in threadsafe mode, so
1015  *      we only need to remove them in this case.
1016  */
1017 static void
1018 destroy_ssl_system(void)
1019 {
1020 #ifdef ENABLE_THREAD_SAFETY
1021         /* Mutex is created in initialize_ssl_system() */
1022         if (pthread_mutex_lock(&ssl_config_mutex))
1023                 return;
1024
1025         if (pq_init_crypto_lib && ssl_open_connections > 0)
1026                 --ssl_open_connections;
1027
1028         if (pq_init_crypto_lib && ssl_open_connections == 0)
1029         {
1030                 /* No connections left, unregister libcrypto callbacks */
1031                 CRYPTO_set_locking_callback(NULL);
1032                 CRYPTO_set_id_callback(NULL);
1033
1034                 /*
1035                  * We don't free the lock array or the SSL_context. If we get another
1036                  * connection in this process, we will just re-use them with the
1037                  * existing mutexes.
1038                  *
1039                  * This means we leak a little memory on repeated load/unload of the
1040                  * library.
1041                  */
1042         }
1043
1044         pthread_mutex_unlock(&ssl_config_mutex);
1045 #endif
1046 }
1047
1048 /*
1049  *      Initialize (potentially) per-connection SSL data, namely the
1050  *      client certificate, private key, and trusted CA certs.
1051  *
1052  *      conn->ssl must already be created.      It receives the connection's client
1053  *      certificate and private key.  Note however that certificates also get
1054  *      loaded into the SSL_context object, and are therefore accessible to all
1055  *      connections in this process.  This should be OK as long as there aren't
1056  *      any hash collisions among the certs.
1057  *
1058  *      Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
1059  */
1060 static int
1061 initialize_SSL(PGconn *conn)
1062 {
1063         struct stat buf;
1064         char            homedir[MAXPGPATH];
1065         char            fnbuf[MAXPGPATH];
1066         char            sebuf[256];
1067         bool            have_homedir;
1068         bool            have_cert;
1069         EVP_PKEY   *pkey = NULL;
1070
1071         /*
1072          * We'll need the home directory if any of the relevant parameters are
1073          * defaulted.  If pqGetHomeDirectory fails, act as though none of the
1074          * files could be found.
1075          */
1076         if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
1077                 !(conn->sslkey && strlen(conn->sslkey) > 0) ||
1078                 !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
1079                 !(conn->sslcrl && strlen(conn->sslcrl) > 0))
1080                 have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
1081         else    /* won't need it */
1082                 have_homedir = false;
1083
1084         /* Read the client certificate file */
1085         if (conn->sslcert && strlen(conn->sslcert) > 0)
1086                 strncpy(fnbuf, conn->sslcert, sizeof(fnbuf));
1087         else if (have_homedir)
1088                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
1089         else
1090                 fnbuf[0] = '\0';
1091
1092         if (fnbuf[0] == '\0')
1093         {
1094                 /* no home directory, proceed without a client cert */
1095                 have_cert = false;
1096         }
1097         else if (stat(fnbuf, &buf) != 0)
1098         {
1099                 /*
1100                  * If file is not present, just go on without a client cert; server
1101                  * might or might not accept the connection.  Any other error,
1102                  * however, is grounds for complaint.
1103                  */
1104                 if (errno != ENOENT && errno != ENOTDIR)
1105                 {
1106                         printfPQExpBuffer(&conn->errorMessage,
1107                            libpq_gettext("could not open certificate file \"%s\": %s\n"),
1108                                                           fnbuf, pqStrerror(errno, sebuf, sizeof(sebuf)));
1109                         return -1;
1110                 }
1111                 have_cert = false;
1112         }
1113         else
1114         {
1115                 /*
1116                  * Cert file exists, so load it.  Since OpenSSL doesn't provide the
1117                  * equivalent of "SSL_use_certificate_chain_file", we actually have to
1118                  * load the file twice.  The first call loads any extra certs after
1119                  * the first one into chain-cert storage associated with the
1120                  * SSL_context.  The second call loads the first cert (only) into the
1121                  * SSL object, where it will be correctly paired with the private key
1122                  * we load below.  We do it this way so that each connection
1123                  * understands which subject cert to present, in case different
1124                  * sslcert settings are used for different connections in the same
1125                  * process.
1126                  *
1127                  * NOTE: This function may also modify our SSL_context and therefore
1128                  * we have to lock around this call and any places where we use the
1129                  * SSL_context struct.
1130                  */
1131 #ifdef ENABLE_THREAD_SAFETY
1132                 int rc;
1133
1134                 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
1135                 {
1136                         printfPQExpBuffer(&conn->errorMessage,
1137                                                           libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
1138                         return -1;
1139                 }
1140 #endif
1141                 if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1142                 {
1143                         char       *err = SSLerrmessage();
1144
1145                         printfPQExpBuffer(&conn->errorMessage,
1146                            libpq_gettext("could not read certificate file \"%s\": %s\n"),
1147                                                           fnbuf, err);
1148                         SSLerrfree(err);
1149
1150 #ifdef ENABLE_THREAD_SAFETY
1151                         pthread_mutex_unlock(&ssl_config_mutex);
1152 #endif
1153                         return -1;
1154                 }
1155
1156                 if (SSL_use_certificate_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1157                 {
1158                         char       *err = SSLerrmessage();
1159
1160                         printfPQExpBuffer(&conn->errorMessage,
1161                            libpq_gettext("could not read certificate file \"%s\": %s\n"),
1162                                                           fnbuf, err);
1163                         SSLerrfree(err);
1164 #ifdef ENABLE_THREAD_SAFETY
1165                         pthread_mutex_unlock(&ssl_config_mutex);
1166 #endif
1167                         return -1;
1168                 }
1169
1170                 /* need to load the associated private key, too */
1171                 have_cert = true;
1172
1173 #ifdef ENABLE_THREAD_SAFETY
1174                 pthread_mutex_unlock(&ssl_config_mutex);
1175 #endif
1176         }
1177
1178         /*
1179          * Read the SSL key. If a key is specified, treat it as an engine:key
1180          * combination if there is colon present - we don't support files with
1181          * colon in the name. The exception is if the second character is a colon,
1182          * in which case it can be a Windows filename with drive specification.
1183          */
1184         if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1185         {
1186 #ifdef USE_SSL_ENGINE
1187                 if (strchr(conn->sslkey, ':')
1188 #ifdef WIN32
1189                         && conn->sslkey[1] != ':'
1190 #endif
1191                         )
1192                 {
1193                         /* Colon, but not in second character, treat as engine:key */
1194                         char       *engine_str = strdup(conn->sslkey);
1195                         char       *engine_colon;
1196
1197                         if (engine_str == NULL)
1198                         {
1199                                 printfPQExpBuffer(&conn->errorMessage,
1200                                                                   libpq_gettext("out of memory\n"));
1201                                 return -1;
1202                         }
1203
1204                         /* cannot return NULL because we already checked before strdup */
1205                         engine_colon = strchr(engine_str, ':');
1206
1207                         *engine_colon = '\0';           /* engine_str now has engine name */
1208                         engine_colon++;         /* engine_colon now has key name */
1209
1210                         conn->engine = ENGINE_by_id(engine_str);
1211                         if (conn->engine == NULL)
1212                         {
1213                                 char       *err = SSLerrmessage();
1214
1215                                 printfPQExpBuffer(&conn->errorMessage,
1216                                          libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1217                                                                   engine_str, err);
1218                                 SSLerrfree(err);
1219                                 free(engine_str);
1220                                 return -1;
1221                         }
1222
1223                         if (ENGINE_init(conn->engine) == 0)
1224                         {
1225                                 char       *err = SSLerrmessage();
1226
1227                                 printfPQExpBuffer(&conn->errorMessage,
1228                                 libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1229                                                                   engine_str, err);
1230                                 SSLerrfree(err);
1231                                 ENGINE_free(conn->engine);
1232                                 conn->engine = NULL;
1233                                 free(engine_str);
1234                                 return -1;
1235                         }
1236
1237                         pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1238                                                                                    NULL, NULL);
1239                         if (pkey == NULL)
1240                         {
1241                                 char       *err = SSLerrmessage();
1242
1243                                 printfPQExpBuffer(&conn->errorMessage,
1244                                                                   libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1245                                                                   engine_colon, engine_str, err);
1246                                 SSLerrfree(err);
1247                                 ENGINE_finish(conn->engine);
1248                                 ENGINE_free(conn->engine);
1249                                 conn->engine = NULL;
1250                                 free(engine_str);
1251                                 return -1;
1252                         }
1253                         if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1254                         {
1255                                 char       *err = SSLerrmessage();
1256
1257                                 printfPQExpBuffer(&conn->errorMessage,
1258                                                                   libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1259                                                                   engine_colon, engine_str, err);
1260                                 SSLerrfree(err);
1261                                 ENGINE_finish(conn->engine);
1262                                 ENGINE_free(conn->engine);
1263                                 conn->engine = NULL;
1264                                 free(engine_str);
1265                                 return -1;
1266                         }
1267
1268                         free(engine_str);
1269
1270                         fnbuf[0] = '\0';        /* indicate we're not going to load from a
1271                                                                  * file */
1272                 }
1273                 else
1274 #endif   /* USE_SSL_ENGINE */
1275                 {
1276                         /* PGSSLKEY is not an engine, treat it as a filename */
1277                         strncpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1278                 }
1279         }
1280         else if (have_homedir)
1281         {
1282                 /* No PGSSLKEY specified, load default file */
1283                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1284         }
1285         else
1286                 fnbuf[0] = '\0';
1287
1288         if (have_cert && fnbuf[0] != '\0')
1289         {
1290                 /* read the client key from file */
1291
1292                 if (stat(fnbuf, &buf) != 0)
1293                 {
1294                         printfPQExpBuffer(&conn->errorMessage,
1295                                                           libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1296                                                           fnbuf);
1297                         return -1;
1298                 }
1299 #ifndef WIN32
1300                 if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1301                 {
1302                         printfPQExpBuffer(&conn->errorMessage,
1303                                                           libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1304                                                           fnbuf);
1305                         return -1;
1306                 }
1307 #endif
1308
1309                 if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1310                 {
1311                         char       *err = SSLerrmessage();
1312
1313                         printfPQExpBuffer(&conn->errorMessage,
1314                            libpq_gettext("could not load private key file \"%s\": %s\n"),
1315                                                           fnbuf, err);
1316                         SSLerrfree(err);
1317                         return -1;
1318                 }
1319         }
1320
1321         /* verify that the cert and key go together */
1322         if (have_cert &&
1323                 SSL_check_private_key(conn->ssl) != 1)
1324         {
1325                 char       *err = SSLerrmessage();
1326
1327                 printfPQExpBuffer(&conn->errorMessage,
1328                                                   libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1329                                                   fnbuf, err);
1330                 SSLerrfree(err);
1331                 return -1;
1332         }
1333
1334         /*
1335          * If the root cert file exists, load it so we can perform certificate
1336          * verification. If sslmode is "verify-full" we will also do further
1337          * verification after the connection has been completed.
1338          */
1339         if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1340                 strncpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1341         else if (have_homedir)
1342                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1343         else
1344                 fnbuf[0] = '\0';
1345
1346         if (fnbuf[0] != '\0' &&
1347                 stat(fnbuf, &buf) == 0)
1348         {
1349                 X509_STORE *cvstore;
1350
1351 #ifdef ENABLE_THREAD_SAFETY
1352                 int rc;
1353
1354                 if ((rc = pthread_mutex_lock(&ssl_config_mutex)))
1355                 {
1356                         printfPQExpBuffer(&conn->errorMessage,
1357                                                           libpq_gettext("could not acquire mutex: %s\n"), strerror(rc));
1358                         return -1;
1359                 }
1360 #endif
1361                 if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1362                 {
1363                         char       *err = SSLerrmessage();
1364
1365                         printfPQExpBuffer(&conn->errorMessage,
1366                                                           libpq_gettext("could not read root certificate file \"%s\": %s\n"),
1367                                                           fnbuf, err);
1368                         SSLerrfree(err);
1369 #ifdef ENABLE_THREAD_SAFETY
1370                         pthread_mutex_unlock(&ssl_config_mutex);
1371 #endif
1372                         return -1;
1373                 }
1374
1375                 if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1376                 {
1377                         if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1378                                 strncpy(fnbuf, conn->sslcrl, sizeof(fnbuf));
1379                         else if (have_homedir)
1380                                 snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1381                         else
1382                                 fnbuf[0] = '\0';
1383
1384                         /* Set the flags to check against the complete CRL chain */
1385                         if (fnbuf[0] != '\0' &&
1386                                 X509_STORE_load_locations(cvstore, fnbuf, NULL) == 1)
1387                         {
1388                                 /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
1389 #ifdef X509_V_FLAG_CRL_CHECK
1390                                 X509_STORE_set_flags(cvstore,
1391                                                   X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1392 #else
1393                                 char       *err = SSLerrmessage();
1394
1395                                 printfPQExpBuffer(&conn->errorMessage,
1396                                                                   libpq_gettext("SSL library does not support CRL certificates (file \"%s\")\n"),
1397                                                                   fnbuf);
1398                                 SSLerrfree(err);
1399 #ifdef ENABLE_THREAD_SAFETY
1400                                 pthread_mutex_unlock(&ssl_config_mutex);
1401 #endif
1402                                 return -1;
1403 #endif
1404                         }
1405                         /* if not found, silently ignore;  we do not require CRL */
1406                 }
1407 #ifdef ENABLE_THREAD_SAFETY
1408                 pthread_mutex_unlock(&ssl_config_mutex);
1409 #endif
1410
1411                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1412         }
1413         else
1414         {
1415                 /*
1416                  * stat() failed; assume root file doesn't exist.  If sslmode is
1417                  * verify-ca or verify-full, this is an error.  Otherwise, continue
1418                  * without performing any server cert verification.
1419                  */
1420                 if (conn->sslmode[0] == 'v')    /* "verify-ca" or "verify-full" */
1421                 {
1422                         /*
1423                          * The only way to reach here with an empty filename is if
1424                          * pqGetHomeDirectory failed.  That's a sufficiently unusual case
1425                          * that it seems worth having a specialized error message for it.
1426                          */
1427                         if (fnbuf[0] == '\0')
1428                                 printfPQExpBuffer(&conn->errorMessage,
1429                                                                   libpq_gettext("could not get home directory to locate root certificate file\n"
1430                                                                                                 "Either provide the file or change sslmode to disable server certificate verification.\n"));
1431                         else
1432                                 printfPQExpBuffer(&conn->errorMessage,
1433                                 libpq_gettext("root certificate file \"%s\" does not exist\n"
1434                                                           "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1435                         return -1;
1436                 }
1437         }
1438
1439         /*
1440          * If the OpenSSL version used supports it (from 1.0.0 on) and the user
1441          * requested it, disable SSL compression.
1442          */
1443 #ifdef SSL_OP_NO_COMPRESSION
1444         if (conn->sslcompression && conn->sslcompression[0] == '0')
1445         {
1446                 SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1447         }
1448 #endif
1449
1450         return 0;
1451 }
1452
1453 static void
1454 destroySSL(void)
1455 {
1456         destroy_ssl_system();
1457 }
1458
1459 /*
1460  *      Attempt to negotiate SSL connection.
1461  */
1462 static PostgresPollingStatusType
1463 open_client_SSL(PGconn *conn)
1464 {
1465         int                     r;
1466
1467         r = SSL_connect(conn->ssl);
1468         if (r <= 0)
1469         {
1470                 int                     err = SSL_get_error(conn->ssl, r);
1471
1472                 switch (err)
1473                 {
1474                         case SSL_ERROR_WANT_READ:
1475                                 return PGRES_POLLING_READING;
1476
1477                         case SSL_ERROR_WANT_WRITE:
1478                                 return PGRES_POLLING_WRITING;
1479
1480                         case SSL_ERROR_SYSCALL:
1481                                 {
1482                                         char            sebuf[256];
1483
1484                                         if (r == -1)
1485                                                 printfPQExpBuffer(&conn->errorMessage,
1486                                                                         libpq_gettext("SSL SYSCALL error: %s\n"),
1487                                                         SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1488                                         else
1489                                                 printfPQExpBuffer(&conn->errorMessage,
1490                                                  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1491                                         close_SSL(conn);
1492                                         return PGRES_POLLING_FAILED;
1493                                 }
1494                         case SSL_ERROR_SSL:
1495                                 {
1496                                         char       *err = SSLerrmessage();
1497
1498                                         printfPQExpBuffer(&conn->errorMessage,
1499                                                                           libpq_gettext("SSL error: %s\n"),
1500                                                                           err);
1501                                         SSLerrfree(err);
1502                                         close_SSL(conn);
1503                                         return PGRES_POLLING_FAILED;
1504                                 }
1505
1506                         default:
1507                                 printfPQExpBuffer(&conn->errorMessage,
1508                                                   libpq_gettext("unrecognized SSL error code: %d\n"),
1509                                                                   err);
1510                                 close_SSL(conn);
1511                                 return PGRES_POLLING_FAILED;
1512                 }
1513         }
1514
1515         /*
1516          * We already checked the server certificate in initialize_SSL() using
1517          * SSL_CTX_set_verify(), if root.crt exists.
1518          */
1519
1520         /* get server certificate */
1521         conn->peer = SSL_get_peer_certificate(conn->ssl);
1522         if (conn->peer == NULL)
1523         {
1524                 char       *err = SSLerrmessage();
1525
1526                 printfPQExpBuffer(&conn->errorMessage,
1527                                         libpq_gettext("certificate could not be obtained: %s\n"),
1528                                                   err);
1529                 SSLerrfree(err);
1530                 close_SSL(conn);
1531                 return PGRES_POLLING_FAILED;
1532         }
1533
1534         if (!verify_peer_name_matches_certificate(conn))
1535         {
1536                 close_SSL(conn);
1537                 return PGRES_POLLING_FAILED;
1538         }
1539
1540         /* SSL handshake is complete */
1541         return PGRES_POLLING_OK;
1542 }
1543
1544 /*
1545  *      Close SSL connection.
1546  */
1547 static void
1548 close_SSL(PGconn *conn)
1549 {
1550         bool destroy_needed = false;
1551
1552         if (conn->ssl)
1553         {
1554                 DECLARE_SIGPIPE_INFO(spinfo);
1555
1556                 /*
1557                  * We can't destroy everything SSL-related here due to the possible
1558                  * later calls to OpenSSL routines which may need our thread
1559                  * callbacks, so set a flag here and check at the end.
1560                  */
1561                 destroy_needed = true;
1562
1563                 DISABLE_SIGPIPE(conn, spinfo, (void) 0);
1564                 SSL_shutdown(conn->ssl);
1565                 SSL_free(conn->ssl);
1566                 conn->ssl = NULL;
1567                 /* We have to assume we got EPIPE */
1568                 REMEMBER_EPIPE(spinfo, true);
1569                 RESTORE_SIGPIPE(conn, spinfo);
1570         }
1571
1572         if (conn->peer)
1573         {
1574                 X509_free(conn->peer);
1575                 conn->peer = NULL;
1576         }
1577
1578 #ifdef USE_SSL_ENGINE
1579         if (conn->engine)
1580         {
1581                 ENGINE_finish(conn->engine);
1582                 ENGINE_free(conn->engine);
1583                 conn->engine = NULL;
1584         }
1585 #endif
1586
1587         /*
1588          * This will remove our SSL locking hooks, if this is the last SSL
1589          * connection, which means we must wait to call it until after all
1590          * SSL calls have been made, otherwise we can end up with a race
1591          * condition and possible deadlocks.
1592          *
1593          * See comments above destroy_ssl_system().
1594          */
1595         if (destroy_needed)
1596                 pqsecure_destroy();
1597 }
1598
1599 /*
1600  * Obtain reason string for last SSL error
1601  *
1602  * Some caution is needed here since ERR_reason_error_string will
1603  * return NULL if it doesn't recognize the error code.  We don't
1604  * want to return NULL ever.
1605  */
1606 static char ssl_nomem[] = "out of memory allocating error description";
1607
1608 #define SSL_ERR_LEN 128
1609
1610 static char *
1611 SSLerrmessage(void)
1612 {
1613         unsigned long errcode;
1614         const char *errreason;
1615         char       *errbuf;
1616
1617         errbuf = malloc(SSL_ERR_LEN);
1618         if (!errbuf)
1619                 return ssl_nomem;
1620         errcode = ERR_get_error();
1621         if (errcode == 0)
1622         {
1623                 snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1624                 return errbuf;
1625         }
1626         errreason = ERR_reason_error_string(errcode);
1627         if (errreason != NULL)
1628         {
1629                 strlcpy(errbuf, errreason, SSL_ERR_LEN);
1630                 return errbuf;
1631         }
1632         snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), errcode);
1633         return errbuf;
1634 }
1635
1636 static void
1637 SSLerrfree(char *buf)
1638 {
1639         if (buf != ssl_nomem)
1640                 free(buf);
1641 }
1642
1643 /*
1644  *      Return pointer to OpenSSL object.
1645  */
1646 void *
1647 PQgetssl(PGconn *conn)
1648 {
1649         if (!conn)
1650                 return NULL;
1651         return conn->ssl;
1652 }
1653 #else                                                   /* !USE_SSL */
1654
1655 void *
1656 PQgetssl(PGconn *conn)
1657 {
1658         return NULL;
1659 }
1660 #endif   /* USE_SSL */
1661
1662
1663 #if defined(ENABLE_THREAD_SAFETY) && !defined(WIN32)
1664
1665 /*
1666  *      Block SIGPIPE for this thread.  This prevents send()/write() from exiting
1667  *      the application.
1668  */
1669 int
1670 pq_block_sigpipe(sigset_t *osigset, bool *sigpipe_pending)
1671 {
1672         sigset_t        sigpipe_sigset;
1673         sigset_t        sigset;
1674
1675         sigemptyset(&sigpipe_sigset);
1676         sigaddset(&sigpipe_sigset, SIGPIPE);
1677
1678         /* Block SIGPIPE and save previous mask for later reset */
1679         SOCK_ERRNO_SET(pthread_sigmask(SIG_BLOCK, &sigpipe_sigset, osigset));
1680         if (SOCK_ERRNO)
1681                 return -1;
1682
1683         /* We can have a pending SIGPIPE only if it was blocked before */
1684         if (sigismember(osigset, SIGPIPE))
1685         {
1686                 /* Is there a pending SIGPIPE? */
1687                 if (sigpending(&sigset) != 0)
1688                         return -1;
1689
1690                 if (sigismember(&sigset, SIGPIPE))
1691                         *sigpipe_pending = true;
1692                 else
1693                         *sigpipe_pending = false;
1694         }
1695         else
1696                 *sigpipe_pending = false;
1697
1698         return 0;
1699 }
1700
1701 /*
1702  *      Discard any pending SIGPIPE and reset the signal mask.
1703  *
1704  * Note: we are effectively assuming here that the C library doesn't queue
1705  * up multiple SIGPIPE events.  If it did, then we'd accidentally leave
1706  * ours in the queue when an event was already pending and we got another.
1707  * As long as it doesn't queue multiple events, we're OK because the caller
1708  * can't tell the difference.
1709  *
1710  * The caller should say got_epipe = FALSE if it is certain that it
1711  * didn't get an EPIPE error; in that case we'll skip the clear operation
1712  * and things are definitely OK, queuing or no.  If it got one or might have
1713  * gotten one, pass got_epipe = TRUE.
1714  *
1715  * We do not want this to change errno, since if it did that could lose
1716  * the error code from a preceding send().      We essentially assume that if
1717  * we were able to do pq_block_sigpipe(), this can't fail.
1718  */
1719 void
1720 pq_reset_sigpipe(sigset_t *osigset, bool sigpipe_pending, bool got_epipe)
1721 {
1722         int                     save_errno = SOCK_ERRNO;
1723         int                     signo;
1724         sigset_t        sigset;
1725
1726         /* Clear SIGPIPE only if none was pending */
1727         if (got_epipe && !sigpipe_pending)
1728         {
1729                 if (sigpending(&sigset) == 0 &&
1730                         sigismember(&sigset, SIGPIPE))
1731                 {
1732                         sigset_t        sigpipe_sigset;
1733
1734                         sigemptyset(&sigpipe_sigset);
1735                         sigaddset(&sigpipe_sigset, SIGPIPE);
1736
1737                         sigwait(&sigpipe_sigset, &signo);
1738                 }
1739         }
1740
1741         /* Restore saved block mask */
1742         pthread_sigmask(SIG_SETMASK, osigset, NULL);
1743
1744         SOCK_ERRNO_SET(save_errno);
1745 }
1746
1747 #endif   /* ENABLE_THREAD_SAFETY && !WIN32 */