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