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