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