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