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