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-2022, 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 
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 #include <netinet/tcp.h>
42 #include <arpa/inet.h>
43 #endif
44 
45 #include <sys/stat.h>
46 
47 #ifdef ENABLE_THREAD_SAFETY
48 #ifdef WIN32
49 #include "pthread-win32.h"
50 #else
51 #include <pthread.h>
52 #endif
53 #endif
54 
55 /*
56  * These SSL-related #includes must come after all system-provided headers.
57  * This ensures that OpenSSL can take care of conflicts with Windows'
58  * <wincrypt.h> by #undef'ing the conflicting macros. (We don't directly
59  * include <wincrypt.h>, but some other Windows headers do.)
60  */
61 #include "common/openssl.h"
62 #include <openssl/conf.h>
63 #ifdef USE_SSL_ENGINE
64 #include <openssl/engine.h>
65 #endif
66 #include <openssl/x509v3.h>
67 
68 
69 static int verify_cb(int ok, X509_STORE_CTX *ctx);
71  ASN1_STRING *name_entry,
72  char **store_name);
74  ASN1_OCTET_STRING *addr_entry,
75  char **store_name);
76 static void destroy_ssl_system(void);
77 static int initialize_SSL(PGconn *conn);
79 static char *SSLerrmessage(unsigned long ecode);
80 static void SSLerrfree(char *buf);
81 static int PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
82 
83 static int my_sock_read(BIO *h, char *buf, int size);
84 static int my_sock_write(BIO *h, const char *buf, int size);
85 static BIO_METHOD *my_BIO_s_socket(void);
86 static int my_SSL_set_fd(PGconn *conn, int fd);
87 
88 
89 static bool pq_init_ssl_lib = true;
90 static bool pq_init_crypto_lib = true;
91 
92 static bool ssl_lib_initialized = false;
93 
94 #ifdef ENABLE_THREAD_SAFETY
95 static long crypto_open_connections = 0;
96 
97 #ifndef WIN32
98 static pthread_mutex_t ssl_config_mutex = PTHREAD_MUTEX_INITIALIZER;
99 #else
100 static pthread_mutex_t ssl_config_mutex = NULL;
101 static long win32_ssl_create_mutex = 0;
102 #endif
103 #endif /* ENABLE_THREAD_SAFETY */
104 
106 static int ssl_protocol_version_to_openssl(const char *protocol);
107 
108 /* ------------------------------------------------------------ */
109 /* Procedures common to all secure sessions */
110 /* ------------------------------------------------------------ */
111 
112 void
113 pgtls_init_library(bool do_ssl, int do_crypto)
114 {
115 #ifdef ENABLE_THREAD_SAFETY
116 
117  /*
118  * Disallow changing the flags while we have open connections, else we'd
119  * get completely confused.
120  */
121  if (crypto_open_connections != 0)
122  return;
123 #endif
124 
125  pq_init_ssl_lib = do_ssl;
126  pq_init_crypto_lib = do_crypto;
127 }
128 
131 {
132  /* First time through? */
133  if (conn->ssl == NULL)
134  {
135  /*
136  * Create a connection-specific SSL object, and load client
137  * certificate, private key, and trusted CA certs.
138  */
139  if (initialize_SSL(conn) != 0)
140  {
141  /* initialize_SSL already put a message in conn->errorMessage */
142  pgtls_close(conn);
143  return PGRES_POLLING_FAILED;
144  }
145  }
146 
147  /* Begin or continue the actual handshake */
148  return open_client_SSL(conn);
149 }
150 
151 ssize_t
152 pgtls_read(PGconn *conn, void *ptr, size_t len)
153 {
154  ssize_t n;
155  int result_errno = 0;
156  char sebuf[PG_STRERROR_R_BUFLEN];
157  int err;
158  unsigned long ecode;
159 
160 rloop:
161 
162  /*
163  * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
164  * queue. In general, the current thread's error queue must be empty
165  * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
166  * not work reliably. Since the possibility exists that other OpenSSL
167  * clients running in the same thread but not under our control will fail
168  * to call ERR_get_error() themselves (after their own I/O operations),
169  * pro-actively clear the per-thread error queue now.
170  */
171  SOCK_ERRNO_SET(0);
172  ERR_clear_error();
173  n = SSL_read(conn->ssl, ptr, len);
174  err = SSL_get_error(conn->ssl, n);
175 
176  /*
177  * Other clients of OpenSSL may fail to call ERR_get_error(), but we
178  * always do, so as to not cause problems for OpenSSL clients that don't
179  * call ERR_clear_error() defensively. Be sure that this happens by
180  * calling now. SSL_get_error() relies on the OpenSSL per-thread error
181  * queue being intact, so this is the earliest possible point
182  * ERR_get_error() may be called.
183  */
184  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
185  switch (err)
186  {
187  case SSL_ERROR_NONE:
188  if (n < 0)
189  {
190  /* Not supposed to happen, so we don't translate the msg */
192  "SSL_read failed but did not provide error information\n");
193  /* assume the connection is broken */
194  result_errno = ECONNRESET;
195  }
196  break;
197  case SSL_ERROR_WANT_READ:
198  n = 0;
199  break;
200  case SSL_ERROR_WANT_WRITE:
201 
202  /*
203  * Returning 0 here would cause caller to wait for read-ready,
204  * which is not correct since what SSL wants is wait for
205  * write-ready. The former could get us stuck in an infinite
206  * wait, so don't risk it; busy-loop instead.
207  */
208  goto rloop;
209  case SSL_ERROR_SYSCALL:
210  if (n < 0)
211  {
212  result_errno = SOCK_ERRNO;
213  if (result_errno == EPIPE ||
214  result_errno == ECONNRESET)
215  libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
216  "\tThis probably means the server terminated abnormally\n"
217  "\tbefore or while processing the request.");
218  else
219  libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
220  SOCK_STRERROR(result_errno,
221  sebuf, sizeof(sebuf)));
222  }
223  else
224  {
225  libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
226  /* assume the connection is broken */
227  result_errno = ECONNRESET;
228  n = -1;
229  }
230  break;
231  case SSL_ERROR_SSL:
232  {
233  char *errm = SSLerrmessage(ecode);
234 
235  libpq_append_conn_error(conn, "SSL error: %s", errm);
236  SSLerrfree(errm);
237  /* assume the connection is broken */
238  result_errno = ECONNRESET;
239  n = -1;
240  break;
241  }
242  case SSL_ERROR_ZERO_RETURN:
243 
244  /*
245  * Per OpenSSL documentation, this error code is only returned for
246  * a clean connection closure, so we should not report it as a
247  * server crash.
248  */
249  libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
250  result_errno = ECONNRESET;
251  n = -1;
252  break;
253  default:
254  libpq_append_conn_error(conn, "unrecognized SSL error code: %d", 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)
315  libpq_append_conn_error(conn, "server closed the connection unexpectedly\n"
316  "\tThis probably means the server terminated abnormally\n"
317  "\tbefore or while processing the request.");
318  else
319  libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
320  SOCK_STRERROR(result_errno,
321  sebuf, sizeof(sebuf)));
322  }
323  else
324  {
325  libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
326  /* assume the connection is broken */
327  result_errno = ECONNRESET;
328  n = -1;
329  }
330  break;
331  case SSL_ERROR_SSL:
332  {
333  char *errm = SSLerrmessage(ecode);
334 
335  libpq_append_conn_error(conn, "SSL error: %s", errm);
336  SSLerrfree(errm);
337  /* assume the connection is broken */
338  result_errno = ECONNRESET;
339  n = -1;
340  break;
341  }
342  case SSL_ERROR_ZERO_RETURN:
343 
344  /*
345  * Per OpenSSL documentation, this error code is only returned for
346  * a clean connection closure, so we should not report it as a
347  * server crash.
348  */
349  libpq_append_conn_error(conn, "SSL connection has been closed unexpectedly");
350  result_errno = ECONNRESET;
351  n = -1;
352  break;
353  default:
354  libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
355  /* assume the connection is broken */
356  result_errno = ECONNRESET;
357  n = -1;
358  break;
359  }
360 
361  /* ensure we return the intended errno to caller */
362  SOCK_ERRNO_SET(result_errno);
363 
364  return n;
365 }
366 
367 #ifdef HAVE_X509_GET_SIGNATURE_NID
368 char *
369 pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
370 {
371  X509 *peer_cert;
372  const EVP_MD *algo_type;
373  unsigned char hash[EVP_MAX_MD_SIZE]; /* size for SHA-512 */
374  unsigned int hash_size;
375  int algo_nid;
376  char *cert_hash;
377 
378  *len = 0;
379 
380  if (!conn->peer)
381  return NULL;
382 
383  peer_cert = conn->peer;
384 
385  /*
386  * Get the signature algorithm of the certificate to determine the hash
387  * algorithm to use for the result.
388  */
389  if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert),
390  &algo_nid, NULL))
391  {
392  libpq_append_conn_error(conn, "could not determine server certificate signature algorithm");
393  return NULL;
394  }
395 
396  /*
397  * The TLS server's certificate bytes need to be hashed with SHA-256 if
398  * its signature algorithm is MD5 or SHA-1 as per RFC 5929
399  * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
400  * is used, the same hash as the signature algorithm is used.
401  */
402  switch (algo_nid)
403  {
404  case NID_md5:
405  case NID_sha1:
406  algo_type = EVP_sha256();
407  break;
408  default:
409  algo_type = EVP_get_digestbynid(algo_nid);
410  if (algo_type == NULL)
411  {
412  libpq_append_conn_error(conn, "could not find digest for NID %s",
413  OBJ_nid2sn(algo_nid));
414  return NULL;
415  }
416  break;
417  }
418 
419  if (!X509_digest(peer_cert, algo_type, hash, &hash_size))
420  {
421  libpq_append_conn_error(conn, "could not generate peer certificate hash");
422  return NULL;
423  }
424 
425  /* save result */
426  cert_hash = malloc(hash_size);
427  if (cert_hash == NULL)
428  {
429  libpq_append_conn_error(conn, "out of memory");
430  return NULL;
431  }
432  memcpy(cert_hash, hash, hash_size);
433  *len = hash_size;
434 
435  return cert_hash;
436 }
437 #endif /* HAVE_X509_GET_SIGNATURE_NID */
438 
439 /* ------------------------------------------------------------ */
440 /* OpenSSL specific code */
441 /* ------------------------------------------------------------ */
442 
443 /*
444  * Certificate verification callback
445  *
446  * This callback allows us to log intermediate problems during
447  * verification, but there doesn't seem to be a clean way to get
448  * our PGconn * structure. So we can't log anything!
449  *
450  * This callback also allows us to override the default acceptance
451  * criteria (e.g., accepting self-signed or expired certs), but
452  * for now we accept the default checks.
453  */
454 static int
455 verify_cb(int ok, X509_STORE_CTX *ctx)
456 {
457  return ok;
458 }
459 
460 
461 /*
462  * OpenSSL-specific wrapper around
463  * pq_verify_peer_name_matches_certificate_name(), converting the ASN1_STRING
464  * into a plain C string.
465  */
466 static int
468  char **store_name)
469 {
470  int len;
471  const unsigned char *namedata;
472 
473  /* Should not happen... */
474  if (name_entry == NULL)
475  {
476  libpq_append_conn_error(conn, "SSL certificate's name entry is missing");
477  return -1;
478  }
479 
480  /*
481  * GEN_DNS can be only IA5String, equivalent to US ASCII.
482  */
483 #ifdef HAVE_ASN1_STRING_GET0_DATA
484  namedata = ASN1_STRING_get0_data(name_entry);
485 #else
486  namedata = ASN1_STRING_data(name_entry);
487 #endif
488  len = ASN1_STRING_length(name_entry);
489 
490  /* OK to cast from unsigned to plain char, since it's all ASCII. */
491  return pq_verify_peer_name_matches_certificate_name(conn, (const char *) namedata, len, store_name);
492 }
493 
494 /*
495  * OpenSSL-specific wrapper around
496  * pq_verify_peer_name_matches_certificate_ip(), converting the
497  * ASN1_OCTET_STRING into a plain C string.
498  */
499 static int
501  ASN1_OCTET_STRING *addr_entry,
502  char **store_name)
503 {
504  int len;
505  const unsigned char *addrdata;
506 
507  /* Should not happen... */
508  if (addr_entry == NULL)
509  {
510  libpq_append_conn_error(conn, "SSL certificate's address entry is missing");
511  return -1;
512  }
513 
514  /*
515  * GEN_IPADD is an OCTET STRING containing an IP address in network byte
516  * order.
517  */
518 #ifdef HAVE_ASN1_STRING_GET0_DATA
519  addrdata = ASN1_STRING_get0_data(addr_entry);
520 #else
521  addrdata = ASN1_STRING_data(addr_entry);
522 #endif
523  len = ASN1_STRING_length(addr_entry);
524 
525  return pq_verify_peer_name_matches_certificate_ip(conn, addrdata, len, store_name);
526 }
527 
528 static bool
529 is_ip_address(const char *host)
530 {
531  struct in_addr dummy4;
532 #ifdef HAVE_INET_PTON
533  struct in6_addr dummy6;
534 #endif
535 
536  return inet_aton(host, &dummy4)
537 #ifdef HAVE_INET_PTON
538  || (inet_pton(AF_INET6, host, &dummy6) == 1)
539 #endif
540  ;
541 }
542 
543 /*
544  * Verify that the server certificate matches the hostname we connected to.
545  *
546  * The certificate's Common Name and Subject Alternative Names are considered.
547  */
548 int
550  int *names_examined,
551  char **first_name)
552 {
553  STACK_OF(GENERAL_NAME) * peer_san;
554  int i;
555  int rc = 0;
556  char *host = conn->connhost[conn->whichhost].host;
557  int host_type;
558  bool check_cn = true;
559 
560  Assert(host && host[0]); /* should be guaranteed by caller */
561 
562  /*
563  * We try to match the NSS behavior here, which is a slight departure from
564  * the spec but seems to make more intuitive sense:
565  *
566  * If connhost contains a DNS name, and the certificate's SANs contain any
567  * dNSName entries, then we'll ignore the Subject Common Name entirely;
568  * otherwise, we fall back to checking the CN. (This behavior matches the
569  * RFC.)
570  *
571  * If connhost contains an IP address, and the SANs contain iPAddress
572  * entries, we again ignore the CN. Otherwise, we allow the CN to match,
573  * EVEN IF there is a dNSName in the SANs. (RFC 6125 prohibits this: "A
574  * client MUST NOT seek a match for a reference identifier of CN-ID if the
575  * presented identifiers include a DNS-ID, SRV-ID, URI-ID, or any
576  * application-specific identifier types supported by the client.")
577  *
578  * NOTE: Prior versions of libpq did not consider iPAddress entries at
579  * all, so this new behavior might break a certificate that has different
580  * IP addresses in the Subject CN and the SANs.
581  */
582  if (is_ip_address(host))
583  host_type = GEN_IPADD;
584  else
585  host_type = GEN_DNS;
586 
587  /*
588  * First, get the Subject Alternative Names (SANs) from the certificate,
589  * and compare them against the originally given hostname.
590  */
591  peer_san = (STACK_OF(GENERAL_NAME) *)
592  X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
593 
594  if (peer_san)
595  {
596  int san_len = sk_GENERAL_NAME_num(peer_san);
597 
598  for (i = 0; i < san_len; i++)
599  {
600  const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
601  char *alt_name = NULL;
602 
603  if (name->type == host_type)
604  {
605  /*
606  * This SAN is of the same type (IP or DNS) as our host name,
607  * so don't allow a fallback check of the CN.
608  */
609  check_cn = false;
610  }
611 
612  if (name->type == GEN_DNS)
613  {
614  (*names_examined)++;
616  name->d.dNSName,
617  &alt_name);
618  }
619  else if (name->type == GEN_IPADD)
620  {
621  (*names_examined)++;
623  name->d.iPAddress,
624  &alt_name);
625  }
626 
627  if (alt_name)
628  {
629  if (!*first_name)
630  *first_name = alt_name;
631  else
632  free(alt_name);
633  }
634 
635  if (rc != 0)
636  {
637  /*
638  * Either we hit an error or a match, and either way we should
639  * not fall back to the CN.
640  */
641  check_cn = false;
642  break;
643  }
644  }
645  sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
646  }
647 
648  /*
649  * If there is no subjectAltName extension of the matching type, check the
650  * Common Name.
651  *
652  * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
653  * dNSName is present, the CN must be ignored. We break this rule if host
654  * is an IP address; see the comment above.)
655  */
656  if (check_cn)
657  {
658  X509_NAME *subject_name;
659 
660  subject_name = X509_get_subject_name(conn->peer);
661  if (subject_name != NULL)
662  {
663  int cn_index;
664 
665  cn_index = X509_NAME_get_index_by_NID(subject_name,
666  NID_commonName, -1);
667  if (cn_index >= 0)
668  {
669  char *common_name = NULL;
670 
671  (*names_examined)++;
673  X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
674  &common_name);
675 
676  if (common_name)
677  {
678  if (!*first_name)
679  *first_name = common_name;
680  else
681  free(common_name);
682  }
683  }
684  }
685  }
686 
687  return rc;
688 }
689 
690 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
691 /*
692  * Callback functions for OpenSSL internal locking. (OpenSSL 1.1.0
693  * does its own locking, and doesn't need these anymore. The
694  * CRYPTO_lock() function was removed in 1.1.0, when the callbacks
695  * were made obsolete, so we assume that if CRYPTO_lock() exists,
696  * the callbacks are still required.)
697  */
698 
699 static unsigned long
700 pq_threadidcallback(void)
701 {
702  /*
703  * This is not standards-compliant. pthread_self() returns pthread_t, and
704  * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
705  * it, so we have to do it.
706  */
707  return (unsigned long) pthread_self();
708 }
709 
710 static pthread_mutex_t *pq_lockarray;
711 
712 static void
713 pq_lockingcallback(int mode, int n, const char *file, int line)
714 {
715  /*
716  * There's no way to report a mutex-primitive failure, so we just Assert
717  * in development builds, and ignore any errors otherwise. Fortunately
718  * this is all obsolete in modern OpenSSL.
719  */
720  if (mode & CRYPTO_LOCK)
721  {
722  if (pthread_mutex_lock(&pq_lockarray[n]))
723  Assert(false);
724  }
725  else
726  {
727  if (pthread_mutex_unlock(&pq_lockarray[n]))
728  Assert(false);
729  }
730 }
731 #endif /* ENABLE_THREAD_SAFETY && HAVE_CRYPTO_LOCK */
732 
733 /*
734  * Initialize SSL library.
735  *
736  * In threadsafe mode, this includes setting up libcrypto callback functions
737  * to do thread locking.
738  *
739  * If the caller has told us (through PQinitOpenSSL) that he's taking care
740  * of libcrypto, we expect that callbacks are already set, and won't try to
741  * override it.
742  */
743 int
744 pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
745 {
746 #ifdef ENABLE_THREAD_SAFETY
747 #ifdef WIN32
748  /* Also see similar code in fe-connect.c, default_threadlock() */
749  if (ssl_config_mutex == NULL)
750  {
751  while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
752  /* loop, another thread own the lock */ ;
753  if (ssl_config_mutex == NULL)
754  {
755  if (pthread_mutex_init(&ssl_config_mutex, NULL))
756  return -1;
757  }
758  InterlockedExchange(&win32_ssl_create_mutex, 0);
759  }
760 #endif
761  if (pthread_mutex_lock(&ssl_config_mutex))
762  return -1;
763 
764 #ifdef HAVE_CRYPTO_LOCK
765  if (pq_init_crypto_lib)
766  {
767  /*
768  * If necessary, set up an array to hold locks for libcrypto.
769  * libcrypto will tell us how big to make this array.
770  */
771  if (pq_lockarray == NULL)
772  {
773  int i;
774 
775  pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
776  if (!pq_lockarray)
777  {
778  pthread_mutex_unlock(&ssl_config_mutex);
779  return -1;
780  }
781  for (i = 0; i < CRYPTO_num_locks(); i++)
782  {
783  if (pthread_mutex_init(&pq_lockarray[i], NULL))
784  {
785  free(pq_lockarray);
786  pq_lockarray = NULL;
787  pthread_mutex_unlock(&ssl_config_mutex);
788  return -1;
789  }
790  }
791  }
792 
793  if (do_crypto && !conn->crypto_loaded)
794  {
795  if (crypto_open_connections++ == 0)
796  {
797  /*
798  * These are only required for threaded libcrypto
799  * applications, but make sure we don't stomp on them if
800  * they're already set.
801  */
802  if (CRYPTO_get_id_callback() == NULL)
803  CRYPTO_set_id_callback(pq_threadidcallback);
804  if (CRYPTO_get_locking_callback() == NULL)
805  CRYPTO_set_locking_callback(pq_lockingcallback);
806  }
807 
808  conn->crypto_loaded = true;
809  }
810  }
811 #endif /* HAVE_CRYPTO_LOCK */
812 #endif /* ENABLE_THREAD_SAFETY */
813 
814  if (!ssl_lib_initialized && do_ssl)
815  {
816  if (pq_init_ssl_lib)
817  {
818 #ifdef HAVE_OPENSSL_INIT_SSL
819  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
820 #else
821  OPENSSL_config(NULL);
822  SSL_library_init();
823  SSL_load_error_strings();
824 #endif
825  }
826  ssl_lib_initialized = true;
827  }
828 
829 #ifdef ENABLE_THREAD_SAFETY
830  pthread_mutex_unlock(&ssl_config_mutex);
831 #endif
832  return 0;
833 }
834 
835 /*
836  * This function is needed because if the libpq library is unloaded
837  * from the application, the callback functions will no longer exist when
838  * libcrypto is used by other parts of the system. For this reason,
839  * we unregister the callback functions when the last libpq
840  * connection is closed. (The same would apply for OpenSSL callbacks
841  * if we had any.)
842  *
843  * Callbacks are only set when we're compiled in threadsafe mode, so
844  * we only need to remove them in this case. They are also not needed
845  * with OpenSSL 1.1.0 anymore.
846  */
847 static void
849 {
850 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
851  /* Mutex is created in pgtls_init() */
852  if (pthread_mutex_lock(&ssl_config_mutex))
853  return;
854 
855  if (pq_init_crypto_lib && crypto_open_connections > 0)
856  --crypto_open_connections;
857 
858  if (pq_init_crypto_lib && crypto_open_connections == 0)
859  {
860  /*
861  * No connections left, unregister libcrypto callbacks, if no one
862  * registered different ones in the meantime.
863  */
864  if (CRYPTO_get_locking_callback() == pq_lockingcallback)
865  CRYPTO_set_locking_callback(NULL);
866  if (CRYPTO_get_id_callback() == pq_threadidcallback)
867  CRYPTO_set_id_callback(NULL);
868 
869  /*
870  * We don't free the lock array. If we get another connection in this
871  * process, we will just re-use them with the existing mutexes.
872  *
873  * This means we leak a little memory on repeated load/unload of the
874  * library.
875  */
876  }
877 
878  pthread_mutex_unlock(&ssl_config_mutex);
879 #endif
880 }
881 
882 /*
883  * Create per-connection SSL object, and load the client certificate,
884  * private key, and trusted CA certs.
885  *
886  * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
887  */
888 static int
890 {
891  SSL_CTX *SSL_context;
892  struct stat buf;
893  char homedir[MAXPGPATH];
894  char fnbuf[MAXPGPATH];
895  char sebuf[PG_STRERROR_R_BUFLEN];
896  bool have_homedir;
897  bool have_cert;
898  bool have_rootcert;
899  EVP_PKEY *pkey = NULL;
900 
901  /*
902  * We'll need the home directory if any of the relevant parameters are
903  * defaulted. If pqGetHomeDirectory fails, act as though none of the
904  * files could be found.
905  */
906  if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
907  !(conn->sslkey && strlen(conn->sslkey) > 0) ||
908  !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
909  !((conn->sslcrl && strlen(conn->sslcrl) > 0) ||
910  (conn->sslcrldir && strlen(conn->sslcrldir) > 0)))
911  have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
912  else /* won't need it */
913  have_homedir = false;
914 
915  /*
916  * Create a new SSL_CTX object.
917  *
918  * We used to share a single SSL_CTX between all connections, but it was
919  * complicated if connections used different certificates. So now we
920  * create a separate context for each connection, and accept the overhead.
921  */
922  SSL_context = SSL_CTX_new(SSLv23_method());
923  if (!SSL_context)
924  {
925  char *err = SSLerrmessage(ERR_get_error());
926 
927  libpq_append_conn_error(conn, "could not create SSL context: %s", err);
928  SSLerrfree(err);
929  return -1;
930  }
931 
932  /*
933  * Delegate the client cert password prompt to the libpq wrapper callback
934  * if any is defined.
935  *
936  * If the application hasn't installed its own and the sslpassword
937  * parameter is non-null, we install ours now to make sure we supply
938  * PGconn->sslpassword to OpenSSL instead of letting it prompt on stdin.
939  *
940  * This will replace OpenSSL's default PEM_def_callback (which prompts on
941  * stdin), but we're only setting it for this SSL context so it's
942  * harmless.
943  */
944  if (PQsslKeyPassHook
945  || (conn->sslpassword && strlen(conn->sslpassword) > 0))
946  {
947  SSL_CTX_set_default_passwd_cb(SSL_context, PQssl_passwd_cb);
948  SSL_CTX_set_default_passwd_cb_userdata(SSL_context, conn);
949  }
950 
951  /* Disable old protocol versions */
952  SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
953 
954  /* Set the minimum and maximum protocol versions if necessary */
956  strlen(conn->ssl_min_protocol_version) != 0)
957  {
958  int ssl_min_ver;
959 
961 
962  if (ssl_min_ver == -1)
963  {
964  libpq_append_conn_error(conn, "invalid value \"%s\" for minimum SSL protocol version",
966  SSL_CTX_free(SSL_context);
967  return -1;
968  }
969 
970  if (!SSL_CTX_set_min_proto_version(SSL_context, ssl_min_ver))
971  {
972  char *err = SSLerrmessage(ERR_get_error());
973 
974  libpq_append_conn_error(conn, "could not set minimum SSL protocol version: %s", err);
975  SSLerrfree(err);
976  SSL_CTX_free(SSL_context);
977  return -1;
978  }
979  }
980 
982  strlen(conn->ssl_max_protocol_version) != 0)
983  {
984  int ssl_max_ver;
985 
987 
988  if (ssl_max_ver == -1)
989  {
990  libpq_append_conn_error(conn, "invalid value \"%s\" for maximum SSL protocol version",
992  SSL_CTX_free(SSL_context);
993  return -1;
994  }
995 
996  if (!SSL_CTX_set_max_proto_version(SSL_context, ssl_max_ver))
997  {
998  char *err = SSLerrmessage(ERR_get_error());
999 
1000  libpq_append_conn_error(conn, "could not set maximum SSL protocol version: %s", err);
1001  SSLerrfree(err);
1002  SSL_CTX_free(SSL_context);
1003  return -1;
1004  }
1005  }
1006 
1007  /*
1008  * Disable OpenSSL's moving-write-buffer sanity check, because it causes
1009  * unnecessary failures in nonblocking send cases.
1010  */
1011  SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1012 
1013  /*
1014  * If the root cert file exists, load it so we can perform certificate
1015  * verification. If sslmode is "verify-full" we will also do further
1016  * verification after the connection has been completed.
1017  */
1018  if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
1019  strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
1020  else if (have_homedir)
1021  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
1022  else
1023  fnbuf[0] = '\0';
1024 
1025  if (fnbuf[0] != '\0' &&
1026  stat(fnbuf, &buf) == 0)
1027  {
1028  X509_STORE *cvstore;
1029 
1030  if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
1031  {
1032  char *err = SSLerrmessage(ERR_get_error());
1033 
1034  libpq_append_conn_error(conn, "could not read root certificate file \"%s\": %s",
1035  fnbuf, err);
1036  SSLerrfree(err);
1037  SSL_CTX_free(SSL_context);
1038  return -1;
1039  }
1040 
1041  if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
1042  {
1043  char *fname = NULL;
1044  char *dname = NULL;
1045 
1046  if (conn->sslcrl && strlen(conn->sslcrl) > 0)
1047  fname = conn->sslcrl;
1048  if (conn->sslcrldir && strlen(conn->sslcrldir) > 0)
1049  dname = conn->sslcrldir;
1050 
1051  /* defaults to use the default CRL file */
1052  if (!fname && !dname && have_homedir)
1053  {
1054  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
1055  fname = fnbuf;
1056  }
1057 
1058  /* Set the flags to check against the complete CRL chain */
1059  if ((fname || dname) &&
1060  X509_STORE_load_locations(cvstore, fname, dname) == 1)
1061  {
1062  X509_STORE_set_flags(cvstore,
1063  X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
1064  }
1065 
1066  /* if not found, silently ignore; we do not require CRL */
1067  ERR_clear_error();
1068  }
1069  have_rootcert = true;
1070  }
1071  else
1072  {
1073  /*
1074  * stat() failed; assume root file doesn't exist. If sslmode is
1075  * verify-ca or verify-full, this is an error. Otherwise, continue
1076  * without performing any server cert verification.
1077  */
1078  if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
1079  {
1080  /*
1081  * The only way to reach here with an empty filename is if
1082  * pqGetHomeDirectory failed. That's a sufficiently unusual case
1083  * that it seems worth having a specialized error message for it.
1084  */
1085  if (fnbuf[0] == '\0')
1086  libpq_append_conn_error(conn, "could not get home directory to locate root certificate file\n"
1087  "Either provide the file or change sslmode to disable server certificate verification.");
1088  else
1089  libpq_append_conn_error(conn, "root certificate file \"%s\" does not exist\n"
1090  "Either provide the file or change sslmode to disable server certificate verification.", fnbuf);
1091  SSL_CTX_free(SSL_context);
1092  return -1;
1093  }
1094  have_rootcert = false;
1095  }
1096 
1097  /* Read the client certificate file */
1098  if (conn->sslcert && strlen(conn->sslcert) > 0)
1099  strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
1100  else if (have_homedir)
1101  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
1102  else
1103  fnbuf[0] = '\0';
1104 
1105  if (fnbuf[0] == '\0')
1106  {
1107  /* no home directory, proceed without a client cert */
1108  have_cert = false;
1109  }
1110  else if (stat(fnbuf, &buf) != 0)
1111  {
1112  /*
1113  * If file is not present, just go on without a client cert; server
1114  * might or might not accept the connection. Any other error,
1115  * however, is grounds for complaint.
1116  */
1117  if (errno != ENOENT && errno != ENOTDIR)
1118  {
1119  libpq_append_conn_error(conn, "could not open certificate file \"%s\": %s",
1120  fnbuf, strerror_r(errno, sebuf, sizeof(sebuf)));
1121  SSL_CTX_free(SSL_context);
1122  return -1;
1123  }
1124  have_cert = false;
1125  }
1126  else
1127  {
1128  /*
1129  * Cert file exists, so load it. Since OpenSSL doesn't provide the
1130  * equivalent of "SSL_use_certificate_chain_file", we have to load it
1131  * into the SSL context, rather than the SSL object.
1132  */
1133  if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1134  {
1135  char *err = SSLerrmessage(ERR_get_error());
1136 
1137  libpq_append_conn_error(conn, "could not read certificate file \"%s\": %s",
1138  fnbuf, err);
1139  SSLerrfree(err);
1140  SSL_CTX_free(SSL_context);
1141  return -1;
1142  }
1143 
1144  /* need to load the associated private key, too */
1145  have_cert = true;
1146  }
1147 
1148  /*
1149  * The SSL context is now loaded with the correct root and client
1150  * certificates. Create a connection-specific SSL object. The private key
1151  * is loaded directly into the SSL object. (We could load the private key
1152  * into the context, too, but we have done it this way historically, and
1153  * it doesn't really matter.)
1154  */
1155  if (!(conn->ssl = SSL_new(SSL_context)) ||
1156  !SSL_set_app_data(conn->ssl, conn) ||
1158  {
1159  char *err = SSLerrmessage(ERR_get_error());
1160 
1161  libpq_append_conn_error(conn, "could not establish SSL connection: %s", err);
1162  SSLerrfree(err);
1163  SSL_CTX_free(SSL_context);
1164  return -1;
1165  }
1166  conn->ssl_in_use = true;
1167 
1168  /*
1169  * SSL contexts are reference counted by OpenSSL. We can free it as soon
1170  * as we have created the SSL object, and it will stick around for as long
1171  * as it's actually needed.
1172  */
1173  SSL_CTX_free(SSL_context);
1174  SSL_context = NULL;
1175 
1176  /*
1177  * Set Server Name Indication (SNI), if enabled by connection parameters.
1178  * Per RFC 6066, do not set it if the host is a literal IP address (IPv4
1179  * or IPv6).
1180  */
1181  if (conn->sslsni && conn->sslsni[0] == '1')
1182  {
1183  const char *host = conn->connhost[conn->whichhost].host;
1184 
1185  if (host && host[0] &&
1186  !(strspn(host, "0123456789.") == strlen(host) ||
1187  strchr(host, ':')))
1188  {
1189  if (SSL_set_tlsext_host_name(conn->ssl, host) != 1)
1190  {
1191  char *err = SSLerrmessage(ERR_get_error());
1192 
1193  libpq_append_conn_error(conn, "could not set SSL Server Name Indication (SNI): %s", err);
1194  SSLerrfree(err);
1195  return -1;
1196  }
1197  }
1198  }
1199 
1200  /*
1201  * Read the SSL key. If a key is specified, treat it as an engine:key
1202  * combination if there is colon present - we don't support files with
1203  * colon in the name. The exception is if the second character is a colon,
1204  * in which case it can be a Windows filename with drive specification.
1205  */
1206  if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1207  {
1208 #ifdef USE_SSL_ENGINE
1209  if (strchr(conn->sslkey, ':')
1210 #ifdef WIN32
1211  && conn->sslkey[1] != ':'
1212 #endif
1213  )
1214  {
1215  /* Colon, but not in second character, treat as engine:key */
1216  char *engine_str = strdup(conn->sslkey);
1217  char *engine_colon;
1218 
1219  if (engine_str == NULL)
1220  {
1221  libpq_append_conn_error(conn, "out of memory");
1222  return -1;
1223  }
1224 
1225  /* cannot return NULL because we already checked before strdup */
1226  engine_colon = strchr(engine_str, ':');
1227 
1228  *engine_colon = '\0'; /* engine_str now has engine name */
1229  engine_colon++; /* engine_colon now has key name */
1230 
1231  conn->engine = ENGINE_by_id(engine_str);
1232  if (conn->engine == NULL)
1233  {
1234  char *err = SSLerrmessage(ERR_get_error());
1235 
1236  libpq_append_conn_error(conn, "could not load SSL engine \"%s\": %s",
1237  engine_str, err);
1238  SSLerrfree(err);
1239  free(engine_str);
1240  return -1;
1241  }
1242 
1243  if (ENGINE_init(conn->engine) == 0)
1244  {
1245  char *err = SSLerrmessage(ERR_get_error());
1246 
1247  libpq_append_conn_error(conn, "could not initialize SSL engine \"%s\": %s",
1248  engine_str, err);
1249  SSLerrfree(err);
1250  ENGINE_free(conn->engine);
1251  conn->engine = NULL;
1252  free(engine_str);
1253  return -1;
1254  }
1255 
1256  pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1257  NULL, NULL);
1258  if (pkey == NULL)
1259  {
1260  char *err = SSLerrmessage(ERR_get_error());
1261 
1262  libpq_append_conn_error(conn, "could not read private SSL key \"%s\" from engine \"%s\": %s",
1263  engine_colon, engine_str, err);
1264  SSLerrfree(err);
1265  ENGINE_finish(conn->engine);
1266  ENGINE_free(conn->engine);
1267  conn->engine = NULL;
1268  free(engine_str);
1269  return -1;
1270  }
1271  if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1272  {
1273  char *err = SSLerrmessage(ERR_get_error());
1274 
1275  libpq_append_conn_error(conn, "could not load private SSL key \"%s\" from engine \"%s\": %s",
1276  engine_colon, engine_str, err);
1277  SSLerrfree(err);
1278  ENGINE_finish(conn->engine);
1279  ENGINE_free(conn->engine);
1280  conn->engine = NULL;
1281  free(engine_str);
1282  return -1;
1283  }
1284 
1285  free(engine_str);
1286 
1287  fnbuf[0] = '\0'; /* indicate we're not going to load from a
1288  * file */
1289  }
1290  else
1291 #endif /* USE_SSL_ENGINE */
1292  {
1293  /* PGSSLKEY is not an engine, treat it as a filename */
1294  strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1295  }
1296  }
1297  else if (have_homedir)
1298  {
1299  /* No PGSSLKEY specified, load default file */
1300  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1301  }
1302  else
1303  fnbuf[0] = '\0';
1304 
1305  if (have_cert && fnbuf[0] != '\0')
1306  {
1307  /* read the client key from file */
1308 
1309  if (stat(fnbuf, &buf) != 0)
1310  {
1311  if (errno == ENOENT)
1312  libpq_append_conn_error(conn, "certificate present, but not private key file \"%s\"",
1313  fnbuf);
1314  else
1315  libpq_append_conn_error(conn, "could not stat private key file \"%s\": %m",
1316  fnbuf);
1317  return -1;
1318  }
1319 
1320  /* Key file must be a regular file */
1321  if (!S_ISREG(buf.st_mode))
1322  {
1323  libpq_append_conn_error(conn, "private key file \"%s\" is not a regular file",
1324  fnbuf);
1325  return -1;
1326  }
1327 
1328  /*
1329  * Refuse to load world-readable key files. We accept root-owned
1330  * files with mode 0640 or less, so that we can access system-wide
1331  * certificates if we have a supplementary group membership that
1332  * allows us to read 'em. For files with non-root ownership, require
1333  * mode 0600 or less. We need not check the file's ownership exactly;
1334  * if we're able to read it despite it having such restrictive
1335  * permissions, it must have the right ownership.
1336  *
1337  * Note: be very careful about tightening these rules. Some people
1338  * expect, for example, that a client process running as root should
1339  * be able to use a non-root-owned key file.
1340  *
1341  * Note that roughly similar checks are performed in
1342  * src/backend/libpq/be-secure-common.c so any changes here may need
1343  * to be made there as well. However, this code caters for the case
1344  * of current user == root, while that code does not.
1345  *
1346  * Ideally we would do similar permissions checks on Windows, but it
1347  * is not clear how that would work since Unix-style permissions may
1348  * not be available.
1349  */
1350 #if !defined(WIN32) && !defined(__CYGWIN__)
1351  if (buf.st_uid == 0 ?
1352  buf.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO) :
1353  buf.st_mode & (S_IRWXG | S_IRWXO))
1354  {
1356  "private key file \"%s\" has group or world access; file must have permissions u=rw (0600) or less if owned by the current user, or permissions u=rw,g=r (0640) or less if owned by root",
1357  fnbuf);
1358  return -1;
1359  }
1360 #endif
1361 
1362  if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1363  {
1364  char *err = SSLerrmessage(ERR_get_error());
1365 
1366  /*
1367  * We'll try to load the file in DER (binary ASN.1) format, and if
1368  * that fails too, report the original error. This could mask
1369  * issues where there's something wrong with a DER-format cert,
1370  * but we'd have to duplicate openssl's format detection to be
1371  * smarter than this. We can't just probe for a leading -----BEGIN
1372  * because PEM can have leading non-matching lines and blanks.
1373  * OpenSSL doesn't expose its get_name(...) and its PEM routines
1374  * don't differentiate between failure modes in enough detail to
1375  * let us tell the difference between "not PEM, try DER" and
1376  * "wrong password".
1377  */
1378  if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_ASN1) != 1)
1379  {
1380  libpq_append_conn_error(conn, "could not load private key file \"%s\": %s",
1381  fnbuf, err);
1382  SSLerrfree(err);
1383  return -1;
1384  }
1385 
1386  SSLerrfree(err);
1387  }
1388  }
1389 
1390  /* verify that the cert and key go together */
1391  if (have_cert &&
1392  SSL_check_private_key(conn->ssl) != 1)
1393  {
1394  char *err = SSLerrmessage(ERR_get_error());
1395 
1396  libpq_append_conn_error(conn, "certificate does not match private key file \"%s\": %s",
1397  fnbuf, err);
1398  SSLerrfree(err);
1399  return -1;
1400  }
1401 
1402  /*
1403  * If a root cert was loaded, also set our certificate verification
1404  * callback.
1405  */
1406  if (have_rootcert)
1407  SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1408 
1409  /*
1410  * Set compression option if necessary.
1411  */
1412  if (conn->sslcompression && conn->sslcompression[0] == '0')
1413  SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1414  else
1415  SSL_clear_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1416 
1417  return 0;
1418 }
1419 
1420 /*
1421  * Attempt to negotiate SSL connection.
1422  */
1425 {
1426  int r;
1427 
1428  ERR_clear_error();
1429  r = SSL_connect(conn->ssl);
1430  if (r <= 0)
1431  {
1432  int err = SSL_get_error(conn->ssl, r);
1433  unsigned long ecode;
1434 
1435  ecode = ERR_get_error();
1436  switch (err)
1437  {
1438  case SSL_ERROR_WANT_READ:
1439  return PGRES_POLLING_READING;
1440 
1441  case SSL_ERROR_WANT_WRITE:
1442  return PGRES_POLLING_WRITING;
1443 
1444  case SSL_ERROR_SYSCALL:
1445  {
1446  char sebuf[PG_STRERROR_R_BUFLEN];
1447 
1448  if (r == -1)
1449  libpq_append_conn_error(conn, "SSL SYSCALL error: %s",
1450  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1451  else
1452  libpq_append_conn_error(conn, "SSL SYSCALL error: EOF detected");
1453  pgtls_close(conn);
1454  return PGRES_POLLING_FAILED;
1455  }
1456  case SSL_ERROR_SSL:
1457  {
1458  char *err = SSLerrmessage(ecode);
1459 
1460  libpq_append_conn_error(conn, "SSL error: %s", err);
1461  SSLerrfree(err);
1462  switch (ERR_GET_REASON(ecode))
1463  {
1464  /*
1465  * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
1466  * TLSV1_ALERT_PROTOCOL_VERSION have been observed
1467  * when trying to communicate with an old OpenSSL
1468  * library, or when the client and server specify
1469  * disjoint protocol ranges.
1470  * NO_PROTOCOLS_AVAILABLE occurs if there's a
1471  * local misconfiguration (which can happen
1472  * despite our checks, if openssl.cnf injects a
1473  * limit we didn't account for). It's not very
1474  * clear what would make OpenSSL return the other
1475  * codes listed here, but a hint about protocol
1476  * versions seems like it's appropriate for all.
1477  */
1478  case SSL_R_NO_PROTOCOLS_AVAILABLE:
1479  case SSL_R_UNSUPPORTED_PROTOCOL:
1480  case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
1481  case SSL_R_UNKNOWN_PROTOCOL:
1482  case SSL_R_UNKNOWN_SSL_VERSION:
1483  case SSL_R_UNSUPPORTED_SSL_VERSION:
1484  case SSL_R_WRONG_SSL_VERSION:
1485  case SSL_R_WRONG_VERSION_NUMBER:
1486  case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
1487 #ifdef SSL_R_VERSION_TOO_HIGH
1488  case SSL_R_VERSION_TOO_HIGH:
1489  case SSL_R_VERSION_TOO_LOW:
1490 #endif
1491  libpq_append_conn_error(conn, "This may indicate that the server does not support any SSL protocol version between %s and %s.",
1494  MIN_OPENSSL_TLS_VERSION,
1497  MAX_OPENSSL_TLS_VERSION);
1498  break;
1499  default:
1500  break;
1501  }
1502  pgtls_close(conn);
1503  return PGRES_POLLING_FAILED;
1504  }
1505 
1506  default:
1507  libpq_append_conn_error(conn, "unrecognized SSL error code: %d", err);
1508  pgtls_close(conn);
1509  return PGRES_POLLING_FAILED;
1510  }
1511  }
1512 
1513  /*
1514  * We already checked the server certificate in initialize_SSL() using
1515  * SSL_CTX_set_verify(), if root.crt exists.
1516  */
1517 
1518  /* get server certificate */
1519  conn->peer = SSL_get_peer_certificate(conn->ssl);
1520  if (conn->peer == NULL)
1521  {
1522  char *err = SSLerrmessage(ERR_get_error());
1523 
1524  libpq_append_conn_error(conn, "certificate could not be obtained: %s", err);
1525  SSLerrfree(err);
1526  pgtls_close(conn);
1527  return PGRES_POLLING_FAILED;
1528  }
1529 
1531  {
1532  pgtls_close(conn);
1533  return PGRES_POLLING_FAILED;
1534  }
1535 
1536  /* SSL handshake is complete */
1537  return PGRES_POLLING_OK;
1538 }
1539 
1540 void
1542 {
1543  bool destroy_needed = false;
1544 
1545  if (conn->ssl_in_use)
1546  {
1547  if (conn->ssl)
1548  {
1549  /*
1550  * We can't destroy everything SSL-related here due to the
1551  * possible later calls to OpenSSL routines which may need our
1552  * thread callbacks, so set a flag here and check at the end.
1553  */
1554 
1555  SSL_shutdown(conn->ssl);
1556  SSL_free(conn->ssl);
1557  conn->ssl = NULL;
1558  conn->ssl_in_use = false;
1559 
1560  destroy_needed = true;
1561  }
1562 
1563  if (conn->peer)
1564  {
1565  X509_free(conn->peer);
1566  conn->peer = NULL;
1567  }
1568 
1569 #ifdef USE_SSL_ENGINE
1570  if (conn->engine)
1571  {
1572  ENGINE_finish(conn->engine);
1573  ENGINE_free(conn->engine);
1574  conn->engine = NULL;
1575  }
1576 #endif
1577  }
1578  else
1579  {
1580  /*
1581  * In the non-SSL case, just remove the crypto callbacks if the
1582  * connection has then loaded. This code path has no dependency on
1583  * any pending SSL calls.
1584  */
1585  if (conn->crypto_loaded)
1586  destroy_needed = true;
1587  }
1588 
1589  /*
1590  * This will remove our crypto locking hooks if this is the last
1591  * connection using libcrypto which means we must wait to call it until
1592  * after all the potential SSL calls have been made, otherwise we can end
1593  * up with a race condition and possible deadlocks.
1594  *
1595  * See comments above destroy_ssl_system().
1596  */
1597  if (destroy_needed)
1598  {
1600  conn->crypto_loaded = false;
1601  }
1602 }
1603 
1604 
1605 /*
1606  * Obtain reason string for passed SSL errcode
1607  *
1608  * ERR_get_error() is used by caller to get errcode to pass here.
1609  *
1610  * Some caution is needed here since ERR_reason_error_string will
1611  * return NULL if it doesn't recognize the error code. We don't
1612  * want to return NULL ever.
1613  */
1614 static char ssl_nomem[] = "out of memory allocating error description";
1615 
1616 #define SSL_ERR_LEN 128
1617 
1618 static char *
1619 SSLerrmessage(unsigned long ecode)
1620 {
1621  const char *errreason;
1622  char *errbuf;
1623 
1624  errbuf = malloc(SSL_ERR_LEN);
1625  if (!errbuf)
1626  return ssl_nomem;
1627  if (ecode == 0)
1628  {
1629  snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1630  return errbuf;
1631  }
1632  errreason = ERR_reason_error_string(ecode);
1633  if (errreason != NULL)
1634  {
1635  strlcpy(errbuf, errreason, SSL_ERR_LEN);
1636  return errbuf;
1637  }
1638  snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1639  return errbuf;
1640 }
1641 
1642 static void
1644 {
1645  if (buf != ssl_nomem)
1646  free(buf);
1647 }
1648 
1649 /* ------------------------------------------------------------ */
1650 /* SSL information functions */
1651 /* ------------------------------------------------------------ */
1652 
1653 /*
1654  * Return pointer to OpenSSL object.
1655  */
1656 void *
1658 {
1659  if (!conn)
1660  return NULL;
1661  return conn->ssl;
1662 }
1663 
1664 void *
1665 PQsslStruct(PGconn *conn, const char *struct_name)
1666 {
1667  if (!conn)
1668  return NULL;
1669  if (strcmp(struct_name, "OpenSSL") == 0)
1670  return conn->ssl;
1671  return NULL;
1672 }
1673 
1674 const char *const *
1676 {
1677  static const char *const openssl_attrs[] = {
1678  "library",
1679  "key_bits",
1680  "cipher",
1681  "compression",
1682  "protocol",
1683  NULL
1684  };
1685  static const char *const empty_attrs[] = {NULL};
1686 
1687  if (!conn)
1688  {
1689  /* Return attributes of default SSL library */
1690  return openssl_attrs;
1691  }
1692 
1693  /* No attrs for unencrypted connection */
1694  if (conn->ssl == NULL)
1695  return empty_attrs;
1696 
1697  return openssl_attrs;
1698 }
1699 
1700 const char *
1701 PQsslAttribute(PGconn *conn, const char *attribute_name)
1702 {
1703  if (!conn)
1704  {
1705  /* PQsslAttribute(NULL, "library") reports the default SSL library */
1706  if (strcmp(attribute_name, "library") == 0)
1707  return "OpenSSL";
1708  return NULL;
1709  }
1710 
1711  /* All attributes read as NULL for a non-encrypted connection */
1712  if (conn->ssl == NULL)
1713  return NULL;
1714 
1715  if (strcmp(attribute_name, "library") == 0)
1716  return "OpenSSL";
1717 
1718  if (strcmp(attribute_name, "key_bits") == 0)
1719  {
1720  static char sslbits_str[12];
1721  int sslbits;
1722 
1723  SSL_get_cipher_bits(conn->ssl, &sslbits);
1724  snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1725  return sslbits_str;
1726  }
1727 
1728  if (strcmp(attribute_name, "cipher") == 0)
1729  return SSL_get_cipher(conn->ssl);
1730 
1731  if (strcmp(attribute_name, "compression") == 0)
1732  return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1733 
1734  if (strcmp(attribute_name, "protocol") == 0)
1735  return SSL_get_version(conn->ssl);
1736 
1737  return NULL; /* unknown attribute */
1738 }
1739 
1740 /*
1741  * Private substitute BIO: this does the sending and receiving using
1742  * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1743  * functions to disable SIGPIPE and give better error messages on I/O errors.
1744  *
1745  * These functions are closely modelled on the standard socket BIO in OpenSSL;
1746  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1747  * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1748  * to retry; do we need to adopt their logic for that?
1749  */
1750 
1751 #ifndef HAVE_BIO_GET_DATA
1752 #define BIO_get_data(bio) (bio->ptr)
1753 #define BIO_set_data(bio, data) (bio->ptr = data)
1754 #endif
1755 
1756 static BIO_METHOD *my_bio_methods;
1757 
1758 static int
1759 my_sock_read(BIO *h, char *buf, int size)
1760 {
1761  int res;
1762 
1763  res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1764  BIO_clear_retry_flags(h);
1765  if (res < 0)
1766  {
1767  /* If we were interrupted, tell caller to retry */
1768  switch (SOCK_ERRNO)
1769  {
1770 #ifdef EAGAIN
1771  case EAGAIN:
1772 #endif
1773 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1774  case EWOULDBLOCK:
1775 #endif
1776  case EINTR:
1777  BIO_set_retry_read(h);
1778  break;
1779 
1780  default:
1781  break;
1782  }
1783  }
1784 
1785  return res;
1786 }
1787 
1788 static int
1789 my_sock_write(BIO *h, const char *buf, int size)
1790 {
1791  int res;
1792 
1793  res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1794  BIO_clear_retry_flags(h);
1795  if (res < 0)
1796  {
1797  /* If we were interrupted, tell caller to retry */
1798  switch (SOCK_ERRNO)
1799  {
1800 #ifdef EAGAIN
1801  case EAGAIN:
1802 #endif
1803 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1804  case EWOULDBLOCK:
1805 #endif
1806  case EINTR:
1807  BIO_set_retry_write(h);
1808  break;
1809 
1810  default:
1811  break;
1812  }
1813  }
1814 
1815  return res;
1816 }
1817 
1818 static BIO_METHOD *
1820 {
1821  if (!my_bio_methods)
1822  {
1823  BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1824 #ifdef HAVE_BIO_METH_NEW
1825  int my_bio_index;
1826 
1827  my_bio_index = BIO_get_new_index();
1828  if (my_bio_index == -1)
1829  return NULL;
1830  my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
1831  my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1832  if (!my_bio_methods)
1833  return NULL;
1834 
1835  /*
1836  * As of this writing, these functions never fail. But check anyway,
1837  * like OpenSSL's own examples do.
1838  */
1839  if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1840  !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1841  !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1842  !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1843  !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1844  !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1845  !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1846  !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1847  {
1848  BIO_meth_free(my_bio_methods);
1849  my_bio_methods = NULL;
1850  return NULL;
1851  }
1852 #else
1853  my_bio_methods = malloc(sizeof(BIO_METHOD));
1854  if (!my_bio_methods)
1855  return NULL;
1856  memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1857  my_bio_methods->bread = my_sock_read;
1858  my_bio_methods->bwrite = my_sock_write;
1859 #endif
1860  }
1861  return my_bio_methods;
1862 }
1863 
1864 /* This should exactly match OpenSSL's SSL_set_fd except for using my BIO */
1865 static int
1867 {
1868  int ret = 0;
1869  BIO *bio;
1870  BIO_METHOD *bio_method;
1871 
1872  bio_method = my_BIO_s_socket();
1873  if (bio_method == NULL)
1874  {
1875  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1876  goto err;
1877  }
1878  bio = BIO_new(bio_method);
1879  if (bio == NULL)
1880  {
1881  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1882  goto err;
1883  }
1884  BIO_set_data(bio, conn);
1885 
1886  SSL_set_bio(conn->ssl, bio, bio);
1887  BIO_set_fd(bio, fd, BIO_NOCLOSE);
1888  ret = 1;
1889 err:
1890  return ret;
1891 }
1892 
1893 /*
1894  * This is the default handler to return a client cert password from
1895  * conn->sslpassword. Apps may install it explicitly if they want to
1896  * prevent openssl from ever prompting on stdin.
1897  */
1898 int
1900 {
1901  if (conn && conn->sslpassword)
1902  {
1903  if (strlen(conn->sslpassword) + 1 > size)
1904  fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1905  strncpy(buf, conn->sslpassword, size);
1906  buf[size - 1] = '\0';
1907  return strlen(buf);
1908  }
1909  else
1910  {
1911  buf[0] = '\0';
1912  return 0;
1913  }
1914 }
1915 
1918 {
1919  return PQsslKeyPassHook;
1920 }
1921 
1922 void
1924 {
1925  PQsslKeyPassHook = hook;
1926 }
1927 
1928 /*
1929  * Supply a password to decrypt a client certificate.
1930  *
1931  * This must match OpenSSL type pem_password_cb.
1932  */
1933 static int
1934 PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1935 {
1936  PGconn *conn = userdata;
1937 
1938  if (PQsslKeyPassHook)
1939  return PQsslKeyPassHook(buf, size, conn);
1940  else
1941  return PQdefaultSSLKeyPassHook_OpenSSL(buf, size, conn);
1942 }
1943 
1944 /*
1945  * Convert TLS protocol version string to OpenSSL values
1946  *
1947  * If a version is passed that is not supported by the current OpenSSL version,
1948  * then we return -1. If a non-negative value is returned, subsequent code can
1949  * assume it is working with a supported version.
1950  *
1951  * Note: this is rather similar to the backend routine in be-secure-openssl.c,
1952  * so make sure to update both routines if changing this one.
1953  */
1954 static int
1955 ssl_protocol_version_to_openssl(const char *protocol)
1956 {
1957  if (pg_strcasecmp("TLSv1", protocol) == 0)
1958  return TLS1_VERSION;
1959 
1960 #ifdef TLS1_1_VERSION
1961  if (pg_strcasecmp("TLSv1.1", protocol) == 0)
1962  return TLS1_1_VERSION;
1963 #endif
1964 
1965 #ifdef TLS1_2_VERSION
1966  if (pg_strcasecmp("TLSv1.2", protocol) == 0)
1967  return TLS1_2_VERSION;
1968 #endif
1969 
1970 #ifdef TLS1_3_VERSION
1971  if (pg_strcasecmp("TLSv1.3", protocol) == 0)
1972  return TLS1_3_VERSION;
1973 #endif
1974 
1975  return -1;
1976 }
static SSL_CTX * SSL_context
const char * name
Definition: encode.c:561
bool pqGetHomeDirectory(char *buf, int bufsize)
Definition: fe-connect.c:7240
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
Definition: fe-misc.c:1312
int pq_verify_peer_name_matches_certificate_name(PGconn *conn, const char *namedata, size_t namelen, char **store_name)
int pq_verify_peer_name_matches_certificate_ip(PGconn *conn, const unsigned char *ipdata, size_t iplen, char **store_name)
bool pq_verify_peer_name_matches_certificate(PGconn *conn)
static char ssl_nomem[]
static int ssl_protocol_version_to_openssl(const char *protocol)
static void destroy_ssl_system(void)
static int my_SSL_set_fd(PGconn *conn, int fd)
static void SSLerrfree(char *buf)
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void)
int pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn, int *names_examined, char **first_name)
PostgresPollingStatusType pgtls_open_client(PGconn *conn)
bool pgtls_read_pending(PGconn *conn)
static bool pq_init_crypto_lib
int PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
static BIO_METHOD * my_bio_methods
static int openssl_verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry, char **store_name)
void pgtls_init_library(bool do_ssl, int do_crypto)
#define BIO_get_data(bio)
ssize_t pgtls_read(PGconn *conn, void *ptr, size_t len)
static bool ssl_lib_initialized
ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len)
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook
#define SSL_ERR_LEN
int pgtls_init(PGconn *conn, bool do_ssl, bool do_crypto)
static BIO_METHOD * my_BIO_s_socket(void)
const char *const * PQsslAttributeNames(PGconn *conn)
static bool pq_init_ssl_lib
#define BIO_set_data(bio, data)
void * PQgetssl(PGconn *conn)
void * PQsslStruct(PGconn *conn, const char *struct_name)
static int initialize_SSL(PGconn *conn)
static int verify_cb(int ok, X509_STORE_CTX *ctx)
static int PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
static char * SSLerrmessage(unsigned long ecode)
static int openssl_verify_peer_name_matches_certificate_ip(PGconn *conn, ASN1_OCTET_STRING *addr_entry, char **store_name)
static PostgresPollingStatusType open_client_SSL(PGconn *conn)
const char * PQsslAttribute(PGconn *conn, const char *attribute_name)
void pgtls_close(PGconn *conn)
void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook)
static int my_sock_write(BIO *h, const char *buf, int size)
static int my_sock_read(BIO *h, char *buf, int size)
static bool is_ip_address(const char *host)
ssize_t pqsecure_raw_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:230
ssize_t pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:346
#define free(a)
Definition: header.h:65
#define malloc(a)
Definition: header.h:50
int i
Definition: isn.c:73
int(* PQsslKeyPassHook_OpenSSL_type)(char *buf, int size, PGconn *conn)
Definition: libpq-fe.h:665
PostgresPollingStatusType
Definition: libpq-fe.h:85
@ PGRES_POLLING_OK
Definition: libpq-fe.h:89
@ PGRES_POLLING_READING
Definition: libpq-fe.h:87
@ PGRES_POLLING_WRITING
Definition: libpq-fe.h:88
@ PGRES_POLLING_FAILED
Definition: libpq-fe.h:86
#define libpq_gettext(x)
Definition: libpq-int.h:882
#define SOCK_STRERROR
Definition: libpq-int.h:904
#define SOCK_ERRNO
Definition: libpq-int.h:903
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:905
Assert(fmt[strlen(fmt) - 1] !='\n')
static PgChecksumMode mode
Definition: pg_checksums.c:65
#define MAXPGPATH
const void size_t len
static char * buf
Definition: pg_test_fsync.c:67
#define PG_STRERROR_R_BUFLEN
Definition: port.h:256
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
int inet_aton(const char *cp, struct in_addr *addr)
Definition: inet_aton.c:56
#define snprintf
Definition: port.h:238
#define fprintf
Definition: port.h:242
#define strerror_r
Definition: port.h:255
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:367
static int fd(const char *x, int i)
Definition: preproc-init.c:105
int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, int version)
int SSL_CTX_set_min_proto_version(SSL_CTX *ctx, int version)
int pthread_mutex_unlock(pthread_mutex_t *mp)
Definition: pthread-win32.c:54
int pthread_mutex_lock(pthread_mutex_t *mp)
Definition: pthread-win32.c:45
DWORD pthread_self(void)
Definition: pthread-win32.c:18
int pthread_mutex_init(pthread_mutex_t *mp, void *attr)
Definition: pthread-win32.c:35
CRITICAL_SECTION * pthread_mutex_t
Definition: pthread-win32.h:8
static unsigned hash(unsigned *uv, int n)
Definition: rege_dfa.c:715
PGconn * conn
Definition: streamutil.c:54
char * host
Definition: libpq-int.h:338
char * sslrootcert
Definition: libpq-int.h:387
char * sslcompression
Definition: libpq-int.h:383
pgsocket sock
Definition: libpq-int.h:447
char * sslcrldir
Definition: libpq-int.h:389
char * sslcrl
Definition: libpq-int.h:388
char * ssl_max_protocol_version
Definition: libpq-int.h:397
char * sslcert
Definition: libpq-int.h:385
char * sslpassword
Definition: libpq-int.h:386
char * sslmode
Definition: libpq-int.h:382
char * ssl_min_protocol_version
Definition: libpq-int.h:396
PQExpBufferData errorMessage
Definition: libpq-int.h:588
char * sslkey
Definition: libpq-int.h:384
int whichhost
Definition: libpq-int.h:429
char * sslsni
Definition: libpq-int.h:390
pg_conn_host * connhost
Definition: libpq-int.h:430
bool ssl_in_use
Definition: libpq-int.h:520
#define S_IXGRP
Definition: win32_port.h:309
#define stat
Definition: win32_port.h:286
#define S_IRWXG
Definition: win32_port.h:312
#define EINTR
Definition: win32_port.h:369
#define EWOULDBLOCK
Definition: win32_port.h:375
#define S_IRWXO
Definition: win32_port.h:324
#define S_ISREG(m)
Definition: win32_port.h:330
#define ECONNRESET
Definition: win32_port.h:379
#define S_IWGRP
Definition: win32_port.h:306
#define EAGAIN
Definition: win32_port.h:367