PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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 /* 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
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  {
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  {
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);
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
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  {
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++;
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++;
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  {
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  {
680  libpq_gettext("server certificate for \"%s\" does not match host name \"%s\"\n"),
681  first_name, host);
682  }
683  else
684  {
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
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
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 this
872  * 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
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
920  * create 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 
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 causes
939  * 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 
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 
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')
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
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  {
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 it
1068  * 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 
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
1088  * certificates. Create a connection-specific SSL object. The private key
1089  * is loaded directly into the SSL object. (We could load the private key
1090  * into the context, too, but we have done it this way historically, and
1091  * it doesn't really matter.)
1092  */
1093  if (!(conn->ssl = SSL_new(SSL_context)) ||
1094  !SSL_set_app_data(conn->ssl, conn) ||
1095  !my_SSL_set_fd(conn, conn->sock))
1096  {
1097  char *err = SSLerrmessage(ERR_get_error());
1098 
1100  libpq_gettext("could not establish SSL connection: %s\n"),
1101  err);
1102  SSLerrfree(err);
1103  SSL_CTX_free(SSL_context);
1104  return -1;
1105  }
1106  conn->ssl_in_use = true;
1107 
1108  /*
1109  * SSL contexts are reference counted by OpenSSL. We can free it as soon
1110  * as we have created the SSL object, and it will stick around for as long
1111  * as it's actually needed.
1112  */
1113  SSL_CTX_free(SSL_context);
1114  SSL_context = NULL;
1115 
1116  /*
1117  * Read the SSL key. If a key is specified, treat it as an engine:key
1118  * combination if there is colon present - we don't support files with
1119  * colon in the name. The exception is if the second character is a colon,
1120  * in which case it can be a Windows filename with drive specification.
1121  */
1122  if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1123  {
1124 #ifdef USE_SSL_ENGINE
1125  if (strchr(conn->sslkey, ':')
1126 #ifdef WIN32
1127  && conn->sslkey[1] != ':'
1128 #endif
1129  )
1130  {
1131  /* Colon, but not in second character, treat as engine:key */
1132  char *engine_str = strdup(conn->sslkey);
1133  char *engine_colon;
1134 
1135  if (engine_str == NULL)
1136  {
1138  libpq_gettext("out of memory\n"));
1139  return -1;
1140  }
1141 
1142  /* cannot return NULL because we already checked before strdup */
1143  engine_colon = strchr(engine_str, ':');
1144 
1145  *engine_colon = '\0'; /* engine_str now has engine name */
1146  engine_colon++; /* engine_colon now has key name */
1147 
1148  conn->engine = ENGINE_by_id(engine_str);
1149  if (conn->engine == NULL)
1150  {
1151  char *err = SSLerrmessage(ERR_get_error());
1152 
1154  libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1155  engine_str, err);
1156  SSLerrfree(err);
1157  free(engine_str);
1158  return -1;
1159  }
1160 
1161  if (ENGINE_init(conn->engine) == 0)
1162  {
1163  char *err = SSLerrmessage(ERR_get_error());
1164 
1166  libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1167  engine_str, err);
1168  SSLerrfree(err);
1169  ENGINE_free(conn->engine);
1170  conn->engine = NULL;
1171  free(engine_str);
1172  return -1;
1173  }
1174 
1175  pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1176  NULL, NULL);
1177  if (pkey == NULL)
1178  {
1179  char *err = SSLerrmessage(ERR_get_error());
1180 
1182  libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1183  engine_colon, engine_str, err);
1184  SSLerrfree(err);
1185  ENGINE_finish(conn->engine);
1186  ENGINE_free(conn->engine);
1187  conn->engine = NULL;
1188  free(engine_str);
1189  return -1;
1190  }
1191  if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1192  {
1193  char *err = SSLerrmessage(ERR_get_error());
1194 
1196  libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1197  engine_colon, engine_str, err);
1198  SSLerrfree(err);
1199  ENGINE_finish(conn->engine);
1200  ENGINE_free(conn->engine);
1201  conn->engine = NULL;
1202  free(engine_str);
1203  return -1;
1204  }
1205 
1206  free(engine_str);
1207 
1208  fnbuf[0] = '\0'; /* indicate we're not going to load from a
1209  * file */
1210  }
1211  else
1212 #endif /* USE_SSL_ENGINE */
1213  {
1214  /* PGSSLKEY is not an engine, treat it as a filename */
1215  strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1216  }
1217  }
1218  else if (have_homedir)
1219  {
1220  /* No PGSSLKEY specified, load default file */
1221  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1222  }
1223  else
1224  fnbuf[0] = '\0';
1225 
1226  if (have_cert && fnbuf[0] != '\0')
1227  {
1228  /* read the client key from file */
1229 
1230  if (stat(fnbuf, &buf) != 0)
1231  {
1233  libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1234  fnbuf);
1235  return -1;
1236  }
1237 #ifndef WIN32
1238  if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1239  {
1241  libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1242  fnbuf);
1243  return -1;
1244  }
1245 #endif
1246 
1247  if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1248  {
1249  char *err = SSLerrmessage(ERR_get_error());
1250 
1252  libpq_gettext("could not load private key file \"%s\": %s\n"),
1253  fnbuf, err);
1254  SSLerrfree(err);
1255  return -1;
1256  }
1257  }
1258 
1259  /* verify that the cert and key go together */
1260  if (have_cert &&
1261  SSL_check_private_key(conn->ssl) != 1)
1262  {
1263  char *err = SSLerrmessage(ERR_get_error());
1264 
1266  libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1267  fnbuf, err);
1268  SSLerrfree(err);
1269  return -1;
1270  }
1271 
1272  /*
1273  * If a root cert was loaded, also set our certificate verification
1274  * callback.
1275  */
1276  if (have_rootcert)
1277  SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1278 
1279  /*
1280  * If the OpenSSL version used supports it (from 1.0.0 on) and the user
1281  * requested it, disable SSL compression.
1282  */
1283 #ifdef SSL_OP_NO_COMPRESSION
1284  if (conn->sslcompression && conn->sslcompression[0] == '0')
1285  {
1286  SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1287  }
1288 #endif
1289 
1290  return 0;
1291 }
1292 
1293 /*
1294  * Attempt to negotiate SSL connection.
1295  */
1298 {
1299  int r;
1300 
1301  ERR_clear_error();
1302  r = SSL_connect(conn->ssl);
1303  if (r <= 0)
1304  {
1305  int err = SSL_get_error(conn->ssl, r);
1306  unsigned long ecode;
1307 
1308  ecode = ERR_get_error();
1309  switch (err)
1310  {
1311  case SSL_ERROR_WANT_READ:
1312  return PGRES_POLLING_READING;
1313 
1314  case SSL_ERROR_WANT_WRITE:
1315  return PGRES_POLLING_WRITING;
1316 
1317  case SSL_ERROR_SYSCALL:
1318  {
1319  char sebuf[256];
1320 
1321  if (r == -1)
1323  libpq_gettext("SSL SYSCALL error: %s\n"),
1324  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1325  else
1327  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1328  pgtls_close(conn);
1329  return PGRES_POLLING_FAILED;
1330  }
1331  case SSL_ERROR_SSL:
1332  {
1333  char *err = SSLerrmessage(ecode);
1334 
1336  libpq_gettext("SSL error: %s\n"),
1337  err);
1338  SSLerrfree(err);
1339  pgtls_close(conn);
1340  return PGRES_POLLING_FAILED;
1341  }
1342 
1343  default:
1345  libpq_gettext("unrecognized SSL error code: %d\n"),
1346  err);
1347  pgtls_close(conn);
1348  return PGRES_POLLING_FAILED;
1349  }
1350  }
1351 
1352  /*
1353  * We already checked the server certificate in initialize_SSL() using
1354  * SSL_CTX_set_verify(), if root.crt exists.
1355  */
1356 
1357  /* get server certificate */
1358  conn->peer = SSL_get_peer_certificate(conn->ssl);
1359  if (conn->peer == NULL)
1360  {
1361  char *err;
1362 
1363  err = SSLerrmessage(ERR_get_error());
1364 
1366  libpq_gettext("certificate could not be obtained: %s\n"),
1367  err);
1368  SSLerrfree(err);
1369  pgtls_close(conn);
1370  return PGRES_POLLING_FAILED;
1371  }
1372 
1374  {
1375  pgtls_close(conn);
1376  return PGRES_POLLING_FAILED;
1377  }
1378 
1379  /* SSL handshake is complete */
1380  return PGRES_POLLING_OK;
1381 }
1382 
1383 /*
1384  * Close SSL connection.
1385  */
1386 void
1388 {
1389  bool destroy_needed = false;
1390 
1391  if (conn->ssl)
1392  {
1393  /*
1394  * We can't destroy everything SSL-related here due to the possible
1395  * later calls to OpenSSL routines which may need our thread
1396  * callbacks, so set a flag here and check at the end.
1397  */
1398  destroy_needed = true;
1399 
1400  SSL_shutdown(conn->ssl);
1401  SSL_free(conn->ssl);
1402  conn->ssl = NULL;
1403  conn->ssl_in_use = false;
1404  }
1405 
1406  if (conn->peer)
1407  {
1408  X509_free(conn->peer);
1409  conn->peer = NULL;
1410  }
1411 
1412 #ifdef USE_SSL_ENGINE
1413  if (conn->engine)
1414  {
1415  ENGINE_finish(conn->engine);
1416  ENGINE_free(conn->engine);
1417  conn->engine = NULL;
1418  }
1419 #endif
1420 
1421  /*
1422  * This will remove our SSL locking hooks, if this is the last SSL
1423  * connection, which means we must wait to call it until after all SSL
1424  * calls have been made, otherwise we can end up with a race condition and
1425  * possible deadlocks.
1426  *
1427  * See comments above destroy_ssl_system().
1428  */
1429  if (destroy_needed)
1431 }
1432 
1433 
1434 /*
1435  * Obtain reason string for passed SSL errcode
1436  *
1437  * ERR_get_error() is used by caller to get errcode to pass here.
1438  *
1439  * Some caution is needed here since ERR_reason_error_string will
1440  * return NULL if it doesn't recognize the error code. We don't
1441  * want to return NULL ever.
1442  */
1443 static char ssl_nomem[] = "out of memory allocating error description";
1444 
1445 #define SSL_ERR_LEN 128
1446 
1447 static char *
1448 SSLerrmessage(unsigned long ecode)
1449 {
1450  const char *errreason;
1451  char *errbuf;
1452 
1453  errbuf = malloc(SSL_ERR_LEN);
1454  if (!errbuf)
1455  return ssl_nomem;
1456  if (ecode == 0)
1457  {
1458  snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1459  return errbuf;
1460  }
1461  errreason = ERR_reason_error_string(ecode);
1462  if (errreason != NULL)
1463  {
1464  strlcpy(errbuf, errreason, SSL_ERR_LEN);
1465  return errbuf;
1466  }
1467  snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1468  return errbuf;
1469 }
1470 
1471 static void
1473 {
1474  if (buf != ssl_nomem)
1475  free(buf);
1476 }
1477 
1478 /* ------------------------------------------------------------ */
1479 /* SSL information functions */
1480 /* ------------------------------------------------------------ */
1481 
1482 int
1484 {
1485  if (!conn)
1486  return 0;
1487  return conn->ssl_in_use;
1488 }
1489 
1490 /*
1491  * Return pointer to OpenSSL object.
1492  */
1493 void *
1495 {
1496  if (!conn)
1497  return NULL;
1498  return conn->ssl;
1499 }
1500 
1501 void *
1502 PQsslStruct(PGconn *conn, const char *struct_name)
1503 {
1504  if (!conn)
1505  return NULL;
1506  if (strcmp(struct_name, "OpenSSL") == 0)
1507  return conn->ssl;
1508  return NULL;
1509 }
1510 
1511 const char *const *
1513 {
1514  static const char *const result[] = {
1515  "library",
1516  "key_bits",
1517  "cipher",
1518  "compression",
1519  "protocol",
1520  NULL
1521  };
1522 
1523  return result;
1524 }
1525 
1526 const char *
1527 PQsslAttribute(PGconn *conn, const char *attribute_name)
1528 {
1529  if (!conn)
1530  return NULL;
1531  if (conn->ssl == NULL)
1532  return NULL;
1533 
1534  if (strcmp(attribute_name, "library") == 0)
1535  return "OpenSSL";
1536 
1537  if (strcmp(attribute_name, "key_bits") == 0)
1538  {
1539  static char sslbits_str[10];
1540  int sslbits;
1541 
1542  SSL_get_cipher_bits(conn->ssl, &sslbits);
1543  snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1544  return sslbits_str;
1545  }
1546 
1547  if (strcmp(attribute_name, "cipher") == 0)
1548  return SSL_get_cipher(conn->ssl);
1549 
1550  if (strcmp(attribute_name, "compression") == 0)
1551  return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1552 
1553  if (strcmp(attribute_name, "protocol") == 0)
1554  return SSL_get_version(conn->ssl);
1555 
1556  return NULL; /* unknown attribute */
1557 }
1558 
1559 /*
1560  * Private substitute BIO: this does the sending and receiving using
1561  * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1562  * functions to disable SIGPIPE and give better error messages on I/O errors.
1563  *
1564  * These functions are closely modelled on the standard socket BIO in OpenSSL;
1565  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1566  * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1567  * to retry; do we need to adopt their logic for that?
1568  */
1569 
1570 #ifndef HAVE_BIO_GET_DATA
1571 #define BIO_get_data(bio) (bio->ptr)
1572 #define BIO_set_data(bio, data) (bio->ptr = data)
1573 #endif
1574 
1575 static BIO_METHOD *my_bio_methods;
1576 
1577 static int
1578 my_sock_read(BIO *h, char *buf, int size)
1579 {
1580  int res;
1581 
1582  res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1583  BIO_clear_retry_flags(h);
1584  if (res < 0)
1585  {
1586  /* If we were interrupted, tell caller to retry */
1587  switch (SOCK_ERRNO)
1588  {
1589 #ifdef EAGAIN
1590  case EAGAIN:
1591 #endif
1592 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1593  case EWOULDBLOCK:
1594 #endif
1595  case EINTR:
1596  BIO_set_retry_read(h);
1597  break;
1598 
1599  default:
1600  break;
1601  }
1602  }
1603 
1604  return res;
1605 }
1606 
1607 static int
1608 my_sock_write(BIO *h, const char *buf, int size)
1609 {
1610  int res;
1611 
1612  res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1613  BIO_clear_retry_flags(h);
1614  if (res <= 0)
1615  {
1616  /* If we were interrupted, tell caller to retry */
1617  switch (SOCK_ERRNO)
1618  {
1619 #ifdef EAGAIN
1620  case EAGAIN:
1621 #endif
1622 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1623  case EWOULDBLOCK:
1624 #endif
1625  case EINTR:
1626  BIO_set_retry_write(h);
1627  break;
1628 
1629  default:
1630  break;
1631  }
1632  }
1633 
1634  return res;
1635 }
1636 
1637 static BIO_METHOD *
1639 {
1640  if (!my_bio_methods)
1641  {
1642  BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1643 #ifdef HAVE_BIO_METH_NEW
1644  int my_bio_index;
1645 
1646  my_bio_index = BIO_get_new_index();
1647  if (my_bio_index == -1)
1648  return NULL;
1649  my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1650  if (!my_bio_methods)
1651  return NULL;
1652 
1653  /*
1654  * As of this writing, these functions never fail. But check anyway,
1655  * like OpenSSL's own examples do.
1656  */
1657  if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1658  !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1659  !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1660  !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1661  !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1662  !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1663  !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1664  !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1665  {
1666  BIO_meth_free(my_bio_methods);
1667  my_bio_methods = NULL;
1668  return NULL;
1669  }
1670 #else
1671  my_bio_methods = malloc(sizeof(BIO_METHOD));
1672  if (!my_bio_methods)
1673  return NULL;
1674  memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1675  my_bio_methods->bread = my_sock_read;
1676  my_bio_methods->bwrite = my_sock_write;
1677 #endif
1678  }
1679  return my_bio_methods;
1680 }
1681 
1682 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
1683 static int
1685 {
1686  int ret = 0;
1687  BIO *bio;
1688  BIO_METHOD *bio_method;
1689 
1690  bio_method = my_BIO_s_socket();
1691  if (bio_method == NULL)
1692  {
1693  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1694  goto err;
1695  }
1696  bio = BIO_new(bio_method);
1697  if (bio == NULL)
1698  {
1699  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1700  goto err;
1701  }
1702  BIO_set_data(bio, conn);
1703 
1704  SSL_set_bio(conn->ssl, bio, bio);
1705  BIO_set_fd(bio, fd, BIO_NOCLOSE);
1706  ret = 1;
1707 err:
1708  return ret;
1709 }
static bool pq_init_ssl_lib
#define EWOULDBLOCK
Definition: win32.h:291
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)
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 ECONNRESET
Definition: win32.h:295
#define malloc(a)
Definition: header.h:50
#define EAGAIN
Definition: win32.h:283
char * sslkey
Definition: libpq-int.h:354
DWORD pthread_self(void)
Definition: pthread-win32.c:18
#define SOCK_STRERROR
Definition: libpq-int.h:696
char * sslcompression
Definition: libpq-int.h:353
#define SOCK_ERRNO
Definition: libpq-int.h:695
PGconn * conn
Definition: streamutil.c:46
#define MAXPGPATH
static char ssl_nomem[]
int pthread_mutex_lock(pthread_mutex_t *mp)
Definition: pthread-win32.c:45
#define libpq_ngettext(s, p, n)
Definition: libpq-int.h:683
static char * buf
Definition: pg_test_fsync.c:67
bool pgtls_read_pending(PGconn *conn)
static BIO_METHOD * my_bio_methods
static int initialize_SSL(PGconn *conn)
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:697
const char *const * PQsslAttributeNames(PGconn *conn)
static int verify_cb(int ok, X509_STORE_CTX *ctx)
pgsocket sock
Definition: libpq-int.h:400
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)
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:426
#define EINTR
Definition: win32.h:285
char * sslmode
Definition: libpq-int.h:352
static bool pq_init_crypto_lib
#define S_IRWXO
Definition: win32.h:455
PQExpBufferData errorMessage
Definition: libpq-int.h:491
char * PQhost(const PGconn *conn)
Definition: fe-connect.c:5998
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
const char * name
Definition: encode.c:521
#define S_IRWXG
Definition: win32.h:451
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:6516
int PQsslInUse(PGconn *conn)
int i
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
static int wildcard_certificate_match(const char *pattern, const char *string)
#define libpq_gettext(x)
Definition: libpq-int.h:682
static bool ssl_lib_initialized