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-2021, 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-openssl.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 #include "common/openssl.h"
34 
35 #ifdef WIN32
36 #include "win32.h"
37 #else
38 #include <sys/socket.h>
39 #include <unistd.h>
40 #include <netdb.h>
41 #include <netinet/in.h>
42 #ifdef HAVE_NETINET_TCP_H
43 #include <netinet/tcp.h>
44 #endif
45 #include <arpa/inet.h>
46 #endif
47 
48 #include <sys/stat.h>
49 
50 #ifdef ENABLE_THREAD_SAFETY
51 #ifdef WIN32
52 #include "pthread-win32.h"
53 #else
54 #include <pthread.h>
55 #endif
56 #endif
57 
58 #include <openssl/ssl.h>
59 #include <openssl/conf.h>
60 #ifdef USE_SSL_ENGINE
61 #include <openssl/engine.h>
62 #endif
63 #include <openssl/x509v3.h>
64 
65 static int verify_cb(int ok, X509_STORE_CTX *ctx);
67  ASN1_STRING *name,
68  char **store_name);
69 static void destroy_ssl_system(void);
70 static int initialize_SSL(PGconn *conn);
72 static char *SSLerrmessage(unsigned long ecode);
73 static void SSLerrfree(char *buf);
74 static int PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
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 static bool ssl_lib_initialized = false;
86 
87 #ifdef ENABLE_THREAD_SAFETY
88 static long crypto_open_connections = 0;
89 
90 #ifndef WIN32
91 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
92 #else
93 static pthread_mutex_t ssl_config_mutex = NULL;
94 static long win32_ssl_create_mutex = 0;
95 #endif
96 #endif /* ENABLE_THREAD_SAFETY */
97 
99 static int ssl_protocol_version_to_openssl(const char *protocol);
100 
101 /* ------------------------------------------------------------ */
102 /* Procedures common to all secure sessions */
103 /* ------------------------------------------------------------ */
104 
105 void
106 pgtls_init_library(bool do_ssl, int do_crypto)
107 {
108 #ifdef ENABLE_THREAD_SAFETY
109 
110  /*
111  * Disallow changing the flags while we have open connections, else we'd
112  * get completely confused.
113  */
114  if (crypto_open_connections != 0)
115  return;
116 #endif
117 
118  pq_init_ssl_lib = do_ssl;
119  pq_init_crypto_lib = do_crypto;
120 }
121 
124 {
125  /* First time through? */
126  if (conn->ssl == NULL)
127  {
128  /*
129  * Create a connection-specific SSL object, and load client
130  * certificate, private key, and trusted CA certs.
131  */
132  if (initialize_SSL(conn) != 0)
133  {
134  /* initialize_SSL already put a message in conn->errorMessage */
135  pgtls_close(conn);
136  return PGRES_POLLING_FAILED;
137  }
138  }
139 
140  /* Begin or continue the actual handshake */
141  return open_client_SSL(conn);
142 }
143 
144 ssize_t
145 pgtls_read(PGconn *conn, void *ptr, size_t len)
146 {
147  ssize_t n;
148  int result_errno = 0;
149  char sebuf[PG_STRERROR_R_BUFLEN];
150  int err;
151  unsigned long ecode;
152 
153 rloop:
154 
155  /*
156  * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
157  * queue. In general, the current thread's error queue must be empty
158  * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
159  * not work reliably. Since the possibility exists that other OpenSSL
160  * clients running in the same thread but not under our control will fail
161  * to call ERR_get_error() themselves (after their own I/O operations),
162  * pro-actively clear the per-thread error queue now.
163  */
164  SOCK_ERRNO_SET(0);
165  ERR_clear_error();
166  n = SSL_read(conn->ssl, ptr, len);
167  err = SSL_get_error(conn->ssl, n);
168 
169  /*
170  * Other clients of OpenSSL may fail to call ERR_get_error(), but we
171  * always do, so as to not cause problems for OpenSSL clients that don't
172  * call ERR_clear_error() defensively. Be sure that this happens by
173  * calling now. SSL_get_error() relies on the OpenSSL per-thread error
174  * queue being intact, so this is the earliest possible point
175  * ERR_get_error() may be called.
176  */
177  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
178  switch (err)
179  {
180  case SSL_ERROR_NONE:
181  if (n < 0)
182  {
183  /* Not supposed to happen, so we don't translate the msg */
185  "SSL_read failed but did not provide error information\n");
186  /* assume the connection is broken */
187  result_errno = ECONNRESET;
188  }
189  break;
190  case SSL_ERROR_WANT_READ:
191  n = 0;
192  break;
193  case SSL_ERROR_WANT_WRITE:
194 
195  /*
196  * Returning 0 here would cause caller to wait for read-ready,
197  * which is not correct since what SSL wants is wait for
198  * write-ready. The former could get us stuck in an infinite
199  * wait, so don't risk it; busy-loop instead.
200  */
201  goto rloop;
202  case SSL_ERROR_SYSCALL:
203  if (n < 0)
204  {
205  result_errno = SOCK_ERRNO;
206  if (result_errno == EPIPE ||
207  result_errno == ECONNRESET)
209  libpq_gettext("server closed the connection unexpectedly\n"
210  "\tThis probably means the server terminated abnormally\n"
211  "\tbefore or while processing the request.\n"));
212  else
214  libpq_gettext("SSL SYSCALL error: %s\n"),
215  SOCK_STRERROR(result_errno,
216  sebuf, sizeof(sebuf)));
217  }
218  else
219  {
221  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
222  /* assume the connection is broken */
223  result_errno = ECONNRESET;
224  n = -1;
225  }
226  break;
227  case SSL_ERROR_SSL:
228  {
229  char *errm = SSLerrmessage(ecode);
230 
232  libpq_gettext("SSL error: %s\n"), errm);
233  SSLerrfree(errm);
234  /* assume the connection is broken */
235  result_errno = ECONNRESET;
236  n = -1;
237  break;
238  }
239  case SSL_ERROR_ZERO_RETURN:
240 
241  /*
242  * Per OpenSSL documentation, this error code is only returned for
243  * a clean connection closure, so we should not report it as a
244  * server crash.
245  */
247  libpq_gettext("SSL connection has been closed unexpectedly\n"));
248  result_errno = ECONNRESET;
249  n = -1;
250  break;
251  default:
253  libpq_gettext("unrecognized SSL error code: %d\n"),
254  err);
255  /* assume the connection is broken */
256  result_errno = ECONNRESET;
257  n = -1;
258  break;
259  }
260 
261  /* ensure we return the intended errno to caller */
262  SOCK_ERRNO_SET(result_errno);
263 
264  return n;
265 }
266 
267 bool
269 {
270  return SSL_pending(conn->ssl) > 0;
271 }
272 
273 ssize_t
274 pgtls_write(PGconn *conn, const void *ptr, size_t len)
275 {
276  ssize_t n;
277  int result_errno = 0;
278  char sebuf[PG_STRERROR_R_BUFLEN];
279  int err;
280  unsigned long ecode;
281 
282  SOCK_ERRNO_SET(0);
283  ERR_clear_error();
284  n = SSL_write(conn->ssl, ptr, len);
285  err = SSL_get_error(conn->ssl, n);
286  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
287  switch (err)
288  {
289  case SSL_ERROR_NONE:
290  if (n < 0)
291  {
292  /* Not supposed to happen, so we don't translate the msg */
294  "SSL_write failed but did not provide error information\n");
295  /* assume the connection is broken */
296  result_errno = ECONNRESET;
297  }
298  break;
299  case SSL_ERROR_WANT_READ:
300 
301  /*
302  * Returning 0 here causes caller to wait for write-ready, which
303  * is not really the right thing, but it's the best we can do.
304  */
305  n = 0;
306  break;
307  case SSL_ERROR_WANT_WRITE:
308  n = 0;
309  break;
310  case SSL_ERROR_SYSCALL:
311  if (n < 0)
312  {
313  result_errno = SOCK_ERRNO;
314  if (result_errno == EPIPE || result_errno == ECONNRESET)
316  libpq_gettext("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_pop_free(peer_san, GENERAL_NAME_free);
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  X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
581  first_name);
582  }
583  }
584  }
585 
586  return rc;
587 }
588 
589 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
590 /*
591  * Callback functions for OpenSSL internal locking. (OpenSSL 1.1.0
592  * does its own locking, and doesn't need these anymore. The
593  * CRYPTO_lock() function was removed in 1.1.0, when the callbacks
594  * were made obsolete, so we assume that if CRYPTO_lock() exists,
595  * the callbacks are still required.)
596  */
597 
598 static unsigned long
599 pq_threadidcallback(void)
600 {
601  /*
602  * This is not standards-compliant. pthread_self() returns pthread_t, and
603  * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
604  * it, so we have to do it.
605  */
606  return (unsigned long) pthread_self();
607 }
608 
609 static pthread_mutex_t *pq_lockarray;
610 
611 static void
612 pq_lockingcallback(int mode, int n, const char *file, int line)
613 {
614  /*
615  * There's no way to report a mutex-primitive failure, so we just Assert
616  * in development builds, and ignore any errors otherwise. Fortunately
617  * this is all obsolete in modern OpenSSL.
618  */
619  if (mode & CRYPTO_LOCK)
620  {
621  if (pthread_mutex_lock(&pq_lockarray[n]))
622  Assert(false);
623  }
624  else
625  {
626  if (pthread_mutex_unlock(&pq_lockarray[n]))
627  Assert(false);
628  }
629 }
630 #endif /* ENABLE_THREAD_SAFETY && HAVE_CRYPTO_LOCK */
631 
632 /*
633  * Initialize SSL library.
634  *
635  * In threadsafe mode, this includes setting up libcrypto callback functions
636  * to do thread locking.
637  *
638  * If the caller has told us (through PQinitOpenSSL) that he's taking care
639  * of libcrypto, we expect that callbacks are already set, and won't try to
640  * override it.
641  */
642 int
643 pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
644 {
645 #ifdef ENABLE_THREAD_SAFETY
646 #ifdef WIN32
647  /* Also see similar code in fe-connect.c, default_threadlock() */
648  if (ssl_config_mutex == NULL)
649  {
650  while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
651  /* loop, another thread own the lock */ ;
652  if (ssl_config_mutex == NULL)
653  {
654  if (pthread_mutex_init(&ssl_config_mutex, NULL))
655  return -1;
656  }
657  InterlockedExchange(&win32_ssl_create_mutex, 0);
658  }
659 #endif
660  if (pthread_mutex_lock(&ssl_config_mutex))
661  return -1;
662 
663 #ifdef HAVE_CRYPTO_LOCK
664  if (pq_init_crypto_lib)
665  {
666  /*
667  * If necessary, set up an array to hold locks for libcrypto.
668  * libcrypto will tell us how big to make this array.
669  */
670  if (pq_lockarray == NULL)
671  {
672  int i;
673 
674  pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
675  if (!pq_lockarray)
676  {
677  pthread_mutex_unlock(&ssl_config_mutex);
678  return -1;
679  }
680  for (i = 0; i < CRYPTO_num_locks(); i++)
681  {
682  if (pthread_mutex_init(&pq_lockarray[i], NULL))
683  {
684  free(pq_lockarray);
685  pq_lockarray = NULL;
686  pthread_mutex_unlock(&ssl_config_mutex);
687  return -1;
688  }
689  }
690  }
691 
692  if (do_crypto && !conn->crypto_loaded)
693  {
694  if (crypto_open_connections++ == 0)
695  {
696  /*
697  * These are only required for threaded libcrypto
698  * applications, but make sure we don't stomp on them if
699  * they're already set.
700  */
701  if (CRYPTO_get_id_callback() == NULL)
702  CRYPTO_set_id_callback(pq_threadidcallback);
703  if (CRYPTO_get_locking_callback() == NULL)
704  CRYPTO_set_locking_callback(pq_lockingcallback);
705  }
706 
707  conn->crypto_loaded = true;
708  }
709  }
710 #endif /* HAVE_CRYPTO_LOCK */
711 #endif /* ENABLE_THREAD_SAFETY */
712 
713  if (!ssl_lib_initialized && do_ssl)
714  {
715  if (pq_init_ssl_lib)
716  {
717 #ifdef HAVE_OPENSSL_INIT_SSL
718  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
719 #else
720  OPENSSL_config(NULL);
721  SSL_library_init();
722  SSL_load_error_strings();
723 #endif
724  }
725  ssl_lib_initialized = true;
726  }
727 
728 #ifdef ENABLE_THREAD_SAFETY
729  pthread_mutex_unlock(&ssl_config_mutex);
730 #endif
731  return 0;
732 }
733 
734 /*
735  * This function is needed because if the libpq library is unloaded
736  * from the application, the callback functions will no longer exist when
737  * libcrypto is used by other parts of the system. For this reason,
738  * we unregister the callback functions when the last libpq
739  * connection is closed. (The same would apply for OpenSSL callbacks
740  * if we had any.)
741  *
742  * Callbacks are only set when we're compiled in threadsafe mode, so
743  * we only need to remove them in this case. They are also not needed
744  * with OpenSSL 1.1.0 anymore.
745  */
746 static void
748 {
749 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
750  /* Mutex is created in pgtls_init() */
751  if (pthread_mutex_lock(&ssl_config_mutex))
752  return;
753 
754  if (pq_init_crypto_lib && crypto_open_connections > 0)
755  --crypto_open_connections;
756 
757  if (pq_init_crypto_lib && crypto_open_connections == 0)
758  {
759  /*
760  * No connections left, unregister libcrypto callbacks, if no one
761  * registered different ones in the meantime.
762  */
763  if (CRYPTO_get_locking_callback() == pq_lockingcallback)
764  CRYPTO_set_locking_callback(NULL);
765  if (CRYPTO_get_id_callback() == pq_threadidcallback)
766  CRYPTO_set_id_callback(NULL);
767 
768  /*
769  * We don't free the lock array. If we get another connection in this
770  * process, we will just re-use them with the existing mutexes.
771  *
772  * This means we leak a little memory on repeated load/unload of the
773  * library.
774  */
775  }
776 
777  pthread_mutex_unlock(&ssl_config_mutex);
778 #endif
779 }
780 
781 /*
782  * Create per-connection SSL object, and load the client certificate,
783  * private key, and trusted CA certs.
784  *
785  * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
786  */
787 static int
789 {
790  SSL_CTX *SSL_context;
791  struct stat buf;
792  char homedir[MAXPGPATH];
793  char fnbuf[MAXPGPATH];
794  char sebuf[PG_STRERROR_R_BUFLEN];
795  bool have_homedir;
796  bool have_cert;
797  bool have_rootcert;
798  EVP_PKEY *pkey = NULL;
799 
800  /*
801  * We'll need the home directory if any of the relevant parameters are
802  * defaulted. If pqGetHomeDirectory fails, act as though none of the
803  * files could be found.
804  */
805  if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
806  !(conn->sslkey && strlen(conn->sslkey) > 0) ||
807  !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
808  !((conn->sslcrl && strlen(conn->sslcrl) > 0) ||
809  (conn->sslcrldir && strlen(conn->sslcrldir) > 0)))
810  have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
811  else /* won't need it */
812  have_homedir = false;
813 
814  /*
815  * Create a new SSL_CTX object.
816  *
817  * We used to share a single SSL_CTX between all connections, but it was
818  * complicated if connections used different certificates. So now we
819  * create a separate context for each connection, and accept the overhead.
820  */
821  SSL_context = SSL_CTX_new(SSLv23_method());
822  if (!SSL_context)
823  {
824  char *err = SSLerrmessage(ERR_get_error());
825 
827  libpq_gettext("could not create SSL context: %s\n"),
828  err);
829  SSLerrfree(err);
830  return -1;
831  }
832 
833  /*
834  * Delegate the client cert password prompt to the libpq wrapper callback
835  * if any is defined.
836  *
837  * If the application hasn't installed its own and the sslpassword
838  * parameter is non-null, we install ours now to make sure we supply
839  * PGconn->sslpassword to OpenSSL instead of letting it prompt on stdin.
840  *
841  * This will replace OpenSSL's default PEM_def_callback (which prompts on
842  * stdin), but we're only setting it for this SSL context so it's
843  * harmless.
844  */
845  if (PQsslKeyPassHook
846  || (conn->sslpassword && strlen(conn->sslpassword) > 0))
847  {
848  SSL_CTX_set_default_passwd_cb(SSL_context, PQssl_passwd_cb);
849  SSL_CTX_set_default_passwd_cb_userdata(SSL_context, conn);
850  }
851 
852  /* Disable old protocol versions */
853  SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
854 
855  /* Set the minimum and maximum protocol versions if necessary */
856  if (conn->ssl_min_protocol_version &&
857  strlen(conn->ssl_min_protocol_version) != 0)
858  {
859  int ssl_min_ver;
860 
862 
863  if (ssl_min_ver == -1)
864  {
866  libpq_gettext("invalid value \"%s\" for minimum SSL protocol version\n"),
868  SSL_CTX_free(SSL_context);
869  return -1;
870  }
871 
872  if (!SSL_CTX_set_min_proto_version(SSL_context, ssl_min_ver))
873  {
874  char *err = SSLerrmessage(ERR_get_error());
875 
877  libpq_gettext("could not set minimum SSL protocol version: %s\n"),
878  err);
879  SSLerrfree(err);
880  SSL_CTX_free(SSL_context);
881  return -1;
882  }
883  }
884 
885  if (conn->ssl_max_protocol_version &&
886  strlen(conn->ssl_max_protocol_version) != 0)
887  {
888  int ssl_max_ver;
889 
891 
892  if (ssl_max_ver == -1)
893  {
895  libpq_gettext("invalid value \"%s\" for maximum SSL protocol version\n"),
897  SSL_CTX_free(SSL_context);
898  return -1;
899  }
900 
901  if (!SSL_CTX_set_max_proto_version(SSL_context, ssl_max_ver))
902  {
903  char *err = SSLerrmessage(ERR_get_error());
904 
906  libpq_gettext("could not set maximum SSL protocol version: %s\n"),
907  err);
908  SSLerrfree(err);
909  SSL_CTX_free(SSL_context);
910  return -1;
911  }
912  }
913 
914  /*
915  * Disable OpenSSL's moving-write-buffer sanity check, because it causes
916  * unnecessary failures in nonblocking send cases.
917  */
918  SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
919 
920  /*
921  * If the root cert file exists, load it so we can perform certificate
922  * verification. If sslmode is "verify-full" we will also do further
923  * verification after the connection has been completed.
924  */
925  if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
926  strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
927  else if (have_homedir)
928  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
929  else
930  fnbuf[0] = '\0';
931 
932  if (fnbuf[0] != '\0' &&
933  stat(fnbuf, &buf) == 0)
934  {
935  X509_STORE *cvstore;
936 
937  if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
938  {
939  char *err = SSLerrmessage(ERR_get_error());
940 
942  libpq_gettext("could not read root certificate file \"%s\": %s\n"),
943  fnbuf, err);
944  SSLerrfree(err);
945  SSL_CTX_free(SSL_context);
946  return -1;
947  }
948 
949  if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
950  {
951  char *fname = NULL;
952  char *dname = NULL;
953 
954  if (conn->sslcrl && strlen(conn->sslcrl) > 0)
955  fname = conn->sslcrl;
956  if (conn->sslcrldir && strlen(conn->sslcrldir) > 0)
957  dname = conn->sslcrldir;
958 
959  /* defaults to use the default CRL file */
960  if (!fname && !dname && have_homedir)
961  {
962  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
963  fname = fnbuf;
964  }
965 
966  /* Set the flags to check against the complete CRL chain */
967  if ((fname || dname) &&
968  X509_STORE_load_locations(cvstore, fname, dname) == 1)
969  {
970  X509_STORE_set_flags(cvstore,
971  X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
972  }
973 
974  /* if not found, silently ignore; we do not require CRL */
975  ERR_clear_error();
976  }
977  have_rootcert = true;
978  }
979  else
980  {
981  /*
982  * stat() failed; assume root file doesn't exist. If sslmode is
983  * verify-ca or verify-full, this is an error. Otherwise, continue
984  * without performing any server cert verification.
985  */
986  if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
987  {
988  /*
989  * The only way to reach here with an empty filename is if
990  * pqGetHomeDirectory failed. That's a sufficiently unusual case
991  * that it seems worth having a specialized error message for it.
992  */
993  if (fnbuf[0] == '\0')
995  libpq_gettext("could not get home directory to locate root certificate file\n"
996  "Either provide the file or change sslmode to disable server certificate verification.\n"));
997  else
999  libpq_gettext("root certificate file \"%s\" does not exist\n"
1000  "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1001  SSL_CTX_free(SSL_context);
1002  return -1;
1003  }
1004  have_rootcert = false;
1005  }
1006 
1007  /* Read the client certificate file */
1008  if (conn->sslcert && strlen(conn->sslcert) > 0)
1009  strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
1010  else if (have_homedir)
1011  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
1012  else
1013  fnbuf[0] = '\0';
1014 
1015  if (fnbuf[0] == '\0')
1016  {
1017  /* no home directory, proceed without a client cert */
1018  have_cert = false;
1019  }
1020  else if (stat(fnbuf, &buf) != 0)
1021  {
1022  /*
1023  * If file is not present, just go on without a client cert; server
1024  * might or might not accept the connection. Any other error,
1025  * however, is grounds for complaint.
1026  */
1027  if (errno != ENOENT && errno != ENOTDIR)
1028  {
1030  libpq_gettext("could not open certificate file \"%s\": %s\n"),
1031  fnbuf, strerror_r(errno, sebuf, sizeof(sebuf)));
1032  SSL_CTX_free(SSL_context);
1033  return -1;
1034  }
1035  have_cert = false;
1036  }
1037  else
1038  {
1039  /*
1040  * Cert file exists, so load it. Since OpenSSL doesn't provide the
1041  * equivalent of "SSL_use_certificate_chain_file", we have to load it
1042  * into the SSL context, rather than the SSL object.
1043  */
1044  if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1045  {
1046  char *err = SSLerrmessage(ERR_get_error());
1047 
1049  libpq_gettext("could not read certificate file \"%s\": %s\n"),
1050  fnbuf, err);
1051  SSLerrfree(err);
1052  SSL_CTX_free(SSL_context);
1053  return -1;
1054  }
1055 
1056  /* need to load the associated private key, too */
1057  have_cert = true;
1058  }
1059 
1060  /*
1061  * The SSL context is now loaded with the correct root and client
1062  * certificates. Create a connection-specific SSL object. The private key
1063  * is loaded directly into the SSL object. (We could load the private key
1064  * into the context, too, but we have done it this way historically, and
1065  * it doesn't really matter.)
1066  */
1067  if (!(conn->ssl = SSL_new(SSL_context)) ||
1068  !SSL_set_app_data(conn->ssl, conn) ||
1069  !my_SSL_set_fd(conn, conn->sock))
1070  {
1071  char *err = SSLerrmessage(ERR_get_error());
1072 
1074  libpq_gettext("could not establish SSL connection: %s\n"),
1075  err);
1076  SSLerrfree(err);
1077  SSL_CTX_free(SSL_context);
1078  return -1;
1079  }
1080  conn->ssl_in_use = true;
1081 
1082  /*
1083  * SSL contexts are reference counted by OpenSSL. We can free it as soon
1084  * as we have created the SSL object, and it will stick around for as long
1085  * as it's actually needed.
1086  */
1087  SSL_CTX_free(SSL_context);
1088  SSL_context = NULL;
1089 
1090  /*
1091  * Set Server Name Indication (SNI), if enabled by connection parameters.
1092  * Per RFC 6066, do not set it if the host is a literal IP address (IPv4
1093  * or IPv6).
1094  */
1095  if (conn->sslsni && conn->sslsni[0] == '1')
1096  {
1097  const char *host = conn->connhost[conn->whichhost].host;
1098 
1099  if (host && host[0] &&
1100  !(strspn(host, "0123456789.") == strlen(host) ||
1101  strchr(host, ':')))
1102  {
1103  if (SSL_set_tlsext_host_name(conn->ssl, host) != 1)
1104  {
1105  char *err = SSLerrmessage(ERR_get_error());
1106 
1108  libpq_gettext("could not set SSL Server Name Indication (SNI): %s\n"),
1109  err);
1110  SSLerrfree(err);
1111  return -1;
1112  }
1113  }
1114  }
1115 
1116  /*
1117  * Read the SSL key. If a key is specified, treat it as an engine:key
1118  * combination if there is colon present - we don't support files with
1119  * colon in the name. The exception is if the second character is a colon,
1120  * in which case it can be a Windows filename with drive specification.
1121  */
1122  if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1123  {
1124 #ifdef USE_SSL_ENGINE
1125  if (strchr(conn->sslkey, ':')
1126 #ifdef WIN32
1127  && conn->sslkey[1] != ':'
1128 #endif
1129  )
1130  {
1131  /* Colon, but not in second character, treat as engine:key */
1132  char *engine_str = strdup(conn->sslkey);
1133  char *engine_colon;
1134 
1135  if (engine_str == NULL)
1136  {
1138  libpq_gettext("out of memory\n"));
1139  return -1;
1140  }
1141 
1142  /* cannot return NULL because we already checked before strdup */
1143  engine_colon = strchr(engine_str, ':');
1144 
1145  *engine_colon = '\0'; /* engine_str now has engine name */
1146  engine_colon++; /* engine_colon now has key name */
1147 
1148  conn->engine = ENGINE_by_id(engine_str);
1149  if (conn->engine == NULL)
1150  {
1151  char *err = SSLerrmessage(ERR_get_error());
1152 
1154  libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1155  engine_str, err);
1156  SSLerrfree(err);
1157  free(engine_str);
1158  return -1;
1159  }
1160 
1161  if (ENGINE_init(conn->engine) == 0)
1162  {
1163  char *err = SSLerrmessage(ERR_get_error());
1164 
1166  libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1167  engine_str, err);
1168  SSLerrfree(err);
1169  ENGINE_free(conn->engine);
1170  conn->engine = NULL;
1171  free(engine_str);
1172  return -1;
1173  }
1174 
1175  pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1176  NULL, NULL);
1177  if (pkey == NULL)
1178  {
1179  char *err = SSLerrmessage(ERR_get_error());
1180 
1182  libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1183  engine_colon, engine_str, err);
1184  SSLerrfree(err);
1185  ENGINE_finish(conn->engine);
1186  ENGINE_free(conn->engine);
1187  conn->engine = NULL;
1188  free(engine_str);
1189  return -1;
1190  }
1191  if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1192  {
1193  char *err = SSLerrmessage(ERR_get_error());
1194 
1196  libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1197  engine_colon, engine_str, err);
1198  SSLerrfree(err);
1199  ENGINE_finish(conn->engine);
1200  ENGINE_free(conn->engine);
1201  conn->engine = NULL;
1202  free(engine_str);
1203  return -1;
1204  }
1205 
1206  free(engine_str);
1207 
1208  fnbuf[0] = '\0'; /* indicate we're not going to load from a
1209  * file */
1210  }
1211  else
1212 #endif /* USE_SSL_ENGINE */
1213  {
1214  /* PGSSLKEY is not an engine, treat it as a filename */
1215  strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1216  }
1217  }
1218  else if (have_homedir)
1219  {
1220  /* No PGSSLKEY specified, load default file */
1221  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1222  }
1223  else
1224  fnbuf[0] = '\0';
1225 
1226  if (have_cert && fnbuf[0] != '\0')
1227  {
1228  /* read the client key from file */
1229 
1230  if (stat(fnbuf, &buf) != 0)
1231  {
1233  libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1234  fnbuf);
1235  return -1;
1236  }
1237 #ifndef WIN32
1238  if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1239  {
1241  libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1242  fnbuf);
1243  return -1;
1244  }
1245 #endif
1246 
1247  if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1248  {
1249  char *err = SSLerrmessage(ERR_get_error());
1250 
1251  /*
1252  * We'll try to load the file in DER (binary ASN.1) format, and if
1253  * that fails too, report the original error. This could mask
1254  * issues where there's something wrong with a DER-format cert,
1255  * but we'd have to duplicate openssl's format detection to be
1256  * smarter than this. We can't just probe for a leading -----BEGIN
1257  * because PEM can have leading non-matching lines and blanks.
1258  * OpenSSL doesn't expose its get_name(...) and its PEM routines
1259  * don't differentiate between failure modes in enough detail to
1260  * let us tell the difference between "not PEM, try DER" and
1261  * "wrong password".
1262  */
1263  if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_ASN1) != 1)
1264  {
1266  libpq_gettext("could not load private key file \"%s\": %s\n"),
1267  fnbuf, err);
1268  SSLerrfree(err);
1269  return -1;
1270  }
1271 
1272  SSLerrfree(err);
1273 
1274  }
1275  }
1276 
1277  /* verify that the cert and key go together */
1278  if (have_cert &&
1279  SSL_check_private_key(conn->ssl) != 1)
1280  {
1281  char *err = SSLerrmessage(ERR_get_error());
1282 
1284  libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1285  fnbuf, err);
1286  SSLerrfree(err);
1287  return -1;
1288  }
1289 
1290  /*
1291  * If a root cert was loaded, also set our certificate verification
1292  * callback.
1293  */
1294  if (have_rootcert)
1295  SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1296 
1297  /*
1298  * Set compression option if necessary.
1299  */
1300  if (conn->sslcompression && conn->sslcompression[0] == '0')
1301  SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1302  else
1303  SSL_clear_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1304 
1305  return 0;
1306 }
1307 
1308 /*
1309  * Attempt to negotiate SSL connection.
1310  */
1313 {
1314  int r;
1315 
1316  ERR_clear_error();
1317  r = SSL_connect(conn->ssl);
1318  if (r <= 0)
1319  {
1320  int err = SSL_get_error(conn->ssl, r);
1321  unsigned long ecode;
1322 
1323  ecode = ERR_get_error();
1324  switch (err)
1325  {
1326  case SSL_ERROR_WANT_READ:
1327  return PGRES_POLLING_READING;
1328 
1329  case SSL_ERROR_WANT_WRITE:
1330  return PGRES_POLLING_WRITING;
1331 
1332  case SSL_ERROR_SYSCALL:
1333  {
1334  char sebuf[PG_STRERROR_R_BUFLEN];
1335 
1336  if (r == -1)
1338  libpq_gettext("SSL SYSCALL error: %s\n"),
1339  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1340  else
1342  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1343  pgtls_close(conn);
1344  return PGRES_POLLING_FAILED;
1345  }
1346  case SSL_ERROR_SSL:
1347  {
1348  char *err = SSLerrmessage(ecode);
1349 
1351  libpq_gettext("SSL error: %s\n"),
1352  err);
1353  SSLerrfree(err);
1354  switch (ERR_GET_REASON(ecode))
1355  {
1356  /*
1357  * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
1358  * TLSV1_ALERT_PROTOCOL_VERSION have been observed
1359  * when trying to communicate with an old OpenSSL
1360  * library, or when the client and server specify
1361  * disjoint protocol ranges.
1362  * NO_PROTOCOLS_AVAILABLE occurs if there's a
1363  * local misconfiguration (which can happen
1364  * despite our checks, if openssl.cnf injects a
1365  * limit we didn't account for). It's not very
1366  * clear what would make OpenSSL return the other
1367  * codes listed here, but a hint about protocol
1368  * versions seems like it's appropriate for all.
1369  */
1370  case SSL_R_NO_PROTOCOLS_AVAILABLE:
1371  case SSL_R_UNSUPPORTED_PROTOCOL:
1372  case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
1373  case SSL_R_UNKNOWN_PROTOCOL:
1374  case SSL_R_UNKNOWN_SSL_VERSION:
1375  case SSL_R_UNSUPPORTED_SSL_VERSION:
1376  case SSL_R_WRONG_SSL_VERSION:
1377  case SSL_R_WRONG_VERSION_NUMBER:
1378  case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
1379 #ifdef SSL_R_VERSION_TOO_HIGH
1380  case SSL_R_VERSION_TOO_HIGH:
1381  case SSL_R_VERSION_TOO_LOW:
1382 #endif
1384  libpq_gettext("This may indicate that the server does not support any SSL protocol version between %s and %s.\n"),
1385  conn->ssl_min_protocol_version ?
1386  conn->ssl_min_protocol_version :
1387  MIN_OPENSSL_TLS_VERSION,
1388  conn->ssl_max_protocol_version ?
1389  conn->ssl_max_protocol_version :
1390  MAX_OPENSSL_TLS_VERSION);
1391  break;
1392  default:
1393  break;
1394  }
1395  pgtls_close(conn);
1396  return PGRES_POLLING_FAILED;
1397  }
1398 
1399  default:
1401  libpq_gettext("unrecognized SSL error code: %d\n"),
1402  err);
1403  pgtls_close(conn);
1404  return PGRES_POLLING_FAILED;
1405  }
1406  }
1407 
1408  /*
1409  * We already checked the server certificate in initialize_SSL() using
1410  * SSL_CTX_set_verify(), if root.crt exists.
1411  */
1412 
1413  /* get server certificate */
1414  conn->peer = SSL_get_peer_certificate(conn->ssl);
1415  if (conn->peer == NULL)
1416  {
1417  char *err = SSLerrmessage(ERR_get_error());
1418 
1420  libpq_gettext("certificate could not be obtained: %s\n"),
1421  err);
1422  SSLerrfree(err);
1423  pgtls_close(conn);
1424  return PGRES_POLLING_FAILED;
1425  }
1426 
1428  {
1429  pgtls_close(conn);
1430  return PGRES_POLLING_FAILED;
1431  }
1432 
1433  /* SSL handshake is complete */
1434  return PGRES_POLLING_OK;
1435 }
1436 
1437 void
1439 {
1440  bool destroy_needed = false;
1441 
1442  if (conn->ssl_in_use)
1443  {
1444  if (conn->ssl)
1445  {
1446  /*
1447  * We can't destroy everything SSL-related here due to the
1448  * possible later calls to OpenSSL routines which may need our
1449  * thread callbacks, so set a flag here and check at the end.
1450  */
1451 
1452  SSL_shutdown(conn->ssl);
1453  SSL_free(conn->ssl);
1454  conn->ssl = NULL;
1455  conn->ssl_in_use = false;
1456 
1457  destroy_needed = true;
1458  }
1459 
1460  if (conn->peer)
1461  {
1462  X509_free(conn->peer);
1463  conn->peer = NULL;
1464  }
1465 
1466 #ifdef USE_SSL_ENGINE
1467  if (conn->engine)
1468  {
1469  ENGINE_finish(conn->engine);
1470  ENGINE_free(conn->engine);
1471  conn->engine = NULL;
1472  }
1473 #endif
1474  }
1475  else
1476  {
1477  /*
1478  * In the non-SSL case, just remove the crypto callbacks if the
1479  * connection has then loaded. This code path has no dependency on
1480  * any pending SSL calls.
1481  */
1482  if (conn->crypto_loaded)
1483  destroy_needed = true;
1484  }
1485 
1486  /*
1487  * This will remove our crypto locking hooks if this is the last
1488  * connection using libcrypto which means we must wait to call it until
1489  * after all the potential SSL calls have been made, otherwise we can end
1490  * up with a race condition and possible deadlocks.
1491  *
1492  * See comments above destroy_ssl_system().
1493  */
1494  if (destroy_needed)
1495  {
1497  conn->crypto_loaded = false;
1498  }
1499 }
1500 
1501 
1502 /*
1503  * Obtain reason string for passed SSL errcode
1504  *
1505  * ERR_get_error() is used by caller to get errcode to pass here.
1506  *
1507  * Some caution is needed here since ERR_reason_error_string will
1508  * return NULL if it doesn't recognize the error code. We don't
1509  * want to return NULL ever.
1510  */
1511 static char ssl_nomem[] = "out of memory allocating error description";
1512 
1513 #define SSL_ERR_LEN 128
1514 
1515 static char *
1516 SSLerrmessage(unsigned long ecode)
1517 {
1518  const char *errreason;
1519  char *errbuf;
1520 
1521  errbuf = malloc(SSL_ERR_LEN);
1522  if (!errbuf)
1523  return ssl_nomem;
1524  if (ecode == 0)
1525  {
1526  snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1527  return errbuf;
1528  }
1529  errreason = ERR_reason_error_string(ecode);
1530  if (errreason != NULL)
1531  {
1532  strlcpy(errbuf, errreason, SSL_ERR_LEN);
1533  return errbuf;
1534  }
1535  snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1536  return errbuf;
1537 }
1538 
1539 static void
1541 {
1542  if (buf != ssl_nomem)
1543  free(buf);
1544 }
1545 
1546 /* ------------------------------------------------------------ */
1547 /* SSL information functions */
1548 /* ------------------------------------------------------------ */
1549 
1550 /*
1551  * Return pointer to OpenSSL object.
1552  */
1553 void *
1555 {
1556  if (!conn)
1557  return NULL;
1558  return conn->ssl;
1559 }
1560 
1561 void *
1562 PQsslStruct(PGconn *conn, const char *struct_name)
1563 {
1564  if (!conn)
1565  return NULL;
1566  if (strcmp(struct_name, "OpenSSL") == 0)
1567  return conn->ssl;
1568  return NULL;
1569 }
1570 
1571 const char *const *
1573 {
1574  static const char *const result[] = {
1575  "library",
1576  "key_bits",
1577  "cipher",
1578  "compression",
1579  "protocol",
1580  NULL
1581  };
1582 
1583  return result;
1584 }
1585 
1586 const char *
1587 PQsslAttribute(PGconn *conn, const char *attribute_name)
1588 {
1589  if (!conn)
1590  return NULL;
1591  if (conn->ssl == NULL)
1592  return NULL;
1593 
1594  if (strcmp(attribute_name, "library") == 0)
1595  return "OpenSSL";
1596 
1597  if (strcmp(attribute_name, "key_bits") == 0)
1598  {
1599  static char sslbits_str[12];
1600  int sslbits;
1601 
1602  SSL_get_cipher_bits(conn->ssl, &sslbits);
1603  snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1604  return sslbits_str;
1605  }
1606 
1607  if (strcmp(attribute_name, "cipher") == 0)
1608  return SSL_get_cipher(conn->ssl);
1609 
1610  if (strcmp(attribute_name, "compression") == 0)
1611  return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1612 
1613  if (strcmp(attribute_name, "protocol") == 0)
1614  return SSL_get_version(conn->ssl);
1615 
1616  return NULL; /* unknown attribute */
1617 }
1618 
1619 /*
1620  * Private substitute BIO: this does the sending and receiving using
1621  * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1622  * functions to disable SIGPIPE and give better error messages on I/O errors.
1623  *
1624  * These functions are closely modelled on the standard socket BIO in OpenSSL;
1625  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1626  * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1627  * to retry; do we need to adopt their logic for that?
1628  */
1629 
1630 #ifndef HAVE_BIO_GET_DATA
1631 #define BIO_get_data(bio) (bio->ptr)
1632 #define BIO_set_data(bio, data) (bio->ptr = data)
1633 #endif
1634 
1635 static BIO_METHOD *my_bio_methods;
1636 
1637 static int
1638 my_sock_read(BIO *h, char *buf, int size)
1639 {
1640  int res;
1641 
1642  res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1643  BIO_clear_retry_flags(h);
1644  if (res < 0)
1645  {
1646  /* If we were interrupted, tell caller to retry */
1647  switch (SOCK_ERRNO)
1648  {
1649 #ifdef EAGAIN
1650  case EAGAIN:
1651 #endif
1652 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1653  case EWOULDBLOCK:
1654 #endif
1655  case EINTR:
1656  BIO_set_retry_read(h);
1657  break;
1658 
1659  default:
1660  break;
1661  }
1662  }
1663 
1664  return res;
1665 }
1666 
1667 static int
1668 my_sock_write(BIO *h, const char *buf, int size)
1669 {
1670  int res;
1671 
1672  res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1673  BIO_clear_retry_flags(h);
1674  if (res <= 0)
1675  {
1676  /* If we were interrupted, tell caller to retry */
1677  switch (SOCK_ERRNO)
1678  {
1679 #ifdef EAGAIN
1680  case EAGAIN:
1681 #endif
1682 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1683  case EWOULDBLOCK:
1684 #endif
1685  case EINTR:
1686  BIO_set_retry_write(h);
1687  break;
1688 
1689  default:
1690  break;
1691  }
1692  }
1693 
1694  return res;
1695 }
1696 
1697 static BIO_METHOD *
1699 {
1700  if (!my_bio_methods)
1701  {
1702  BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1703 #ifdef HAVE_BIO_METH_NEW
1704  int my_bio_index;
1705 
1706  my_bio_index = BIO_get_new_index();
1707  if (my_bio_index == -1)
1708  return NULL;
1709  my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
1710  my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1711  if (!my_bio_methods)
1712  return NULL;
1713 
1714  /*
1715  * As of this writing, these functions never fail. But check anyway,
1716  * like OpenSSL's own examples do.
1717  */
1718  if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1719  !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1720  !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1721  !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1722  !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1723  !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1724  !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1725  !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1726  {
1727  BIO_meth_free(my_bio_methods);
1728  my_bio_methods = NULL;
1729  return NULL;
1730  }
1731 #else
1732  my_bio_methods = malloc(sizeof(BIO_METHOD));
1733  if (!my_bio_methods)
1734  return NULL;
1735  memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1736  my_bio_methods->bread = my_sock_read;
1737  my_bio_methods->bwrite = my_sock_write;
1738 #endif
1739  }
1740  return my_bio_methods;
1741 }
1742 
1743 /* This should exactly match OpenSSL's SSL_set_fd except for using my BIO */
1744 static int
1746 {
1747  int ret = 0;
1748  BIO *bio;
1749  BIO_METHOD *bio_method;
1750 
1751  bio_method = my_BIO_s_socket();
1752  if (bio_method == NULL)
1753  {
1754  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1755  goto err;
1756  }
1757  bio = BIO_new(bio_method);
1758  if (bio == NULL)
1759  {
1760  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1761  goto err;
1762  }
1763  BIO_set_data(bio, conn);
1764 
1765  SSL_set_bio(conn->ssl, bio, bio);
1766  BIO_set_fd(bio, fd, BIO_NOCLOSE);
1767  ret = 1;
1768 err:
1769  return ret;
1770 }
1771 
1772 /*
1773  * This is the default handler to return a client cert password from
1774  * conn->sslpassword. Apps may install it explicitly if they want to
1775  * prevent openssl from ever prompting on stdin.
1776  */
1777 int
1779 {
1780  if (conn->sslpassword)
1781  {
1782  if (strlen(conn->sslpassword) + 1 > size)
1783  fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1784  strncpy(buf, conn->sslpassword, size);
1785  buf[size - 1] = '\0';
1786  return strlen(buf);
1787  }
1788  else
1789  {
1790  buf[0] = '\0';
1791  return 0;
1792  }
1793 }
1794 
1797 {
1798  return PQsslKeyPassHook;
1799 }
1800 
1801 void
1803 {
1804  PQsslKeyPassHook = hook;
1805 }
1806 
1807 /*
1808  * Supply a password to decrypt a client certificate.
1809  *
1810  * This must match OpenSSL type pem_password_cb.
1811  */
1812 static int
1813 PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1814 {
1815  PGconn *conn = userdata;
1816 
1817  if (PQsslKeyPassHook)
1818  return PQsslKeyPassHook(buf, size, conn);
1819  else
1820  return PQdefaultSSLKeyPassHook_OpenSSL(buf, size, conn);
1821 }
1822 
1823 /*
1824  * Convert TLS protocol version string to OpenSSL values
1825  *
1826  * If a version is passed that is not supported by the current OpenSSL version,
1827  * then we return -1. If a non-negative value is returned, subsequent code can
1828  * assume it is working with a supported version.
1829  *
1830  * Note: this is rather similar to the backend routine in be-secure-openssl.c,
1831  * so make sure to update both routines if changing this one.
1832  */
1833 static int
1834 ssl_protocol_version_to_openssl(const char *protocol)
1835 {
1836  if (pg_strcasecmp("TLSv1", protocol) == 0)
1837  return TLS1_VERSION;
1838 
1839 #ifdef TLS1_1_VERSION
1840  if (pg_strcasecmp("TLSv1.1", protocol) == 0)
1841  return TLS1_1_VERSION;
1842 #endif
1843 
1844 #ifdef TLS1_2_VERSION
1845  if (pg_strcasecmp("TLSv1.2", protocol) == 0)
1846  return TLS1_2_VERSION;
1847 #endif
1848 
1849 #ifdef TLS1_3_VERSION
1850  if (pg_strcasecmp("TLSv1.3", protocol) == 0)
1851  return TLS1_3_VERSION;
1852 #endif
1853 
1854  return -1;
1855 }
static bool pq_init_ssl_lib
CRITICAL_SECTION * pthread_mutex_t
Definition: pthread-win32.h:8
static PgChecksumMode mode
Definition: pg_checksums.c:65
void * PQgetssl(PGconn *conn)
static int my_sock_write(BIO *h, const char *buf, int size)
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:349
static PostgresPollingStatusType open_client_SSL(PGconn *)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
void * PQsslStruct(PGconn *conn, const char *struct_name)
int pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
#define PG_STRERROR_R_BUFLEN
Definition: port.h:235
char * host
Definition: libpq-int.h:335
int PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
int pthread_mutex_init(pthread_mutex_t *mp, void *attr)
Definition: pthread-win32.c:35
char * sslsni
Definition: libpq-int.h:387
char * ssl_min_protocol_version
Definition: libpq-int.h:393
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:232
PostgresPollingStatusType pgtls_open_client(PGconn *conn)
#define fprintf
Definition: port.h:221
#define BIO_set_data(bio, data)
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook
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:381
DWORD pthread_self(void)
Definition: pthread-win32.c:18
#define SOCK_STRERROR
Definition: libpq-int.h:855
char * sslcompression
Definition: libpq-int.h:380
#define SOCK_ERRNO
Definition: libpq-int.h:854
PGconn * conn
Definition: streamutil.c:54
#define MAXPGPATH
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
static char ssl_nomem[]
pg_conn_host * connhost
Definition: libpq-int.h:427
bool ssl_in_use
Definition: libpq-int.h:508
int pthread_mutex_lock(pthread_mutex_t *mp)
Definition: pthread-win32.c:45
static char * buf
Definition: pg_test_fsync.c:68
bool pgtls_read_pending(PGconn *conn)
#define S_IRWXG
Definition: win32_port.h:309
bool pq_verify_peer_name_matches_certificate(PGconn *conn)
void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook)
char * sslpassword
Definition: libpq-int.h:383
static BIO_METHOD * my_bio_methods
static int initialize_SSL(PGconn *conn)
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:856
const char *const * PQsslAttributeNames(PGconn *conn)
static int verify_cb(int ok, X509_STORE_CTX *ctx)
pgsocket sock
Definition: libpq-int.h:444
#define S_ISREG(m)
Definition: win32_port.h:327
static int my_sock_read(BIO *h, char *buf, int size)
static int my_SSL_set_fd(PGconn *conn, int fd)
static void SSLerrfree(char *buf)
void pgtls_close(PGconn *conn)
ssize_t pgtls_read(PGconn *conn, void *ptr, size_t len)
ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len)
int pthread_mutex_unlock(pthread_mutex_t *mp)
Definition: pthread-win32.c:54
unsigned short st_mode
Definition: win32_port.h:268
char * sslmode
Definition: libpq-int.h:379
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:571
char * sslcert
Definition: libpq-int.h:382
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
int SSL_CTX_set_min_proto_version(SSL_CTX *ctx, int version)
#define Assert(condition)
Definition: c.h:804
static int ssl_protocol_version_to_openssl(const char *protocol)
#define strerror_r
Definition: port.h:234
char * sslrootcert
Definition: libpq-int.h:384
ssize_t pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:314
#define ECONNRESET
Definition: win32_port.h:361
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void)
const char * name
Definition: encode.c:561
PostgresPollingStatusType
Definition: libpq-fe.h:82
static char * SSLerrmessage(unsigned long ecode)
static SSL_CTX * SSL_context
char * ssl_max_protocol_version
Definition: libpq-int.h:394
bool pqGetHomeDirectory(char *buf, int bufsize)
Definition: fe-connect.c:7242
int i
char * sslcrldir
Definition: libpq-int.h:386
#define EWOULDBLOCK
Definition: win32_port.h:357
#define EINTR
Definition: win32_port.h:351
void pgtls_init_library(bool do_ssl, int do_crypto)
int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, int version)
int(* PQsslKeyPassHook_OpenSSL_type)(char *buf, int size, PGconn *conn)
Definition: libpq-fe.h:663
static void destroy_ssl_system(void)
static unsigned hash(unsigned *uv, int n)
Definition: rege_dfa.c:715
#define snprintf
Definition: port.h:217
static BIO_METHOD * my_BIO_s_socket(void)
#define SSL_ERR_LEN
#define BIO_get_data(bio)
char * sslcrl
Definition: libpq-int.h:385
#define S_IRWXO
Definition: win32_port.h:321
int whichhost
Definition: libpq-int.h:426
#define libpq_gettext(x)
Definition: libpq-int.h:841
#define stat
Definition: win32_port.h:283
static bool ssl_lib_initialized