PostgreSQL Source Code  git master
be-secure-openssl.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * be-secure-openssl.c
4  * functions for OpenSSL support in the backend.
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/backend/libpq/be-secure-openssl.c
13  *
14  *-------------------------------------------------------------------------
15  */
16 
17 #include "postgres.h"
18 
19 #include <sys/stat.h>
20 #include <signal.h>
21 #include <fcntl.h>
22 #include <ctype.h>
23 #include <sys/socket.h>
24 #include <unistd.h>
25 #include <netdb.h>
26 #include <netinet/in.h>
27 #ifdef HAVE_NETINET_TCP_H
28 #include <netinet/tcp.h>
29 #include <arpa/inet.h>
30 #endif
31 
32 #include "libpq/libpq.h"
33 #include "miscadmin.h"
34 #include "pgstat.h"
35 #include "storage/fd.h"
36 #include "storage/latch.h"
37 #include "tcop/tcopprot.h"
38 #include "utils/memutils.h"
39 
40 /*
41  * These SSL-related #includes must come after all system-provided headers.
42  * This ensures that OpenSSL can take care of conflicts with Windows'
43  * <wincrypt.h> by #undef'ing the conflicting macros. (We don't directly
44  * include <wincrypt.h>, but some other Windows headers do.)
45  */
46 #include "common/openssl.h"
47 #include <openssl/conf.h>
48 #include <openssl/dh.h>
49 #ifndef OPENSSL_NO_ECDH
50 #include <openssl/ec.h>
51 #endif
52 #include <openssl/x509v3.h>
53 
54 
55 /* default init hook can be overridden by a shared library */
56 static void default_openssl_tls_init(SSL_CTX *context, bool isServerStart);
57 openssl_tls_init_hook_typ openssl_tls_init_hook = default_openssl_tls_init;
58 
59 static int my_sock_read(BIO *h, char *buf, int size);
60 static int my_sock_write(BIO *h, const char *buf, int size);
61 static BIO_METHOD *my_BIO_s_socket(void);
62 static int my_SSL_set_fd(Port *port, int fd);
63 
64 static DH *load_dh_file(char *filename, bool isServerStart);
65 static DH *load_dh_buffer(const char *, size_t);
66 static int ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata);
67 static int dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
68 static int verify_cb(int, X509_STORE_CTX *);
69 static void info_cb(const SSL *ssl, int type, int args);
70 static bool initialize_dh(SSL_CTX *context, bool isServerStart);
71 static bool initialize_ecdh(SSL_CTX *context, bool isServerStart);
72 static const char *SSLerrmessage(unsigned long ecode);
73 
74 static char *X509_NAME_to_cstring(X509_NAME *name);
75 
76 static SSL_CTX *SSL_context = NULL;
77 static bool SSL_initialized = false;
78 static bool dummy_ssl_passwd_cb_called = false;
79 static bool ssl_is_server_start;
80 
81 static int ssl_protocol_version_to_openssl(int v);
82 static const char *ssl_protocol_version_to_string(int v);
83 
84 /* ------------------------------------------------------------ */
85 /* Public interface */
86 /* ------------------------------------------------------------ */
87 
88 int
89 be_tls_init(bool isServerStart)
90 {
91  SSL_CTX *context;
92  int ssl_ver_min = -1;
93  int ssl_ver_max = -1;
94 
95  /* This stuff need be done only once. */
96  if (!SSL_initialized)
97  {
98 #ifdef HAVE_OPENSSL_INIT_SSL
99  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
100 #else
101  OPENSSL_config(NULL);
102  SSL_library_init();
103  SSL_load_error_strings();
104 #endif
105  SSL_initialized = true;
106  }
107 
108  /*
109  * Create a new SSL context into which we'll load all the configuration
110  * settings. If we fail partway through, we can avoid memory leakage by
111  * freeing this context; we don't install it as active until the end.
112  *
113  * We use SSLv23_method() because it can negotiate use of the highest
114  * mutually supported protocol version, while alternatives like
115  * TLSv1_2_method() permit only one specific version. Note that we don't
116  * actually allow SSL v2 or v3, only TLS protocols (see below).
117  */
118  context = SSL_CTX_new(SSLv23_method());
119  if (!context)
120  {
121  ereport(isServerStart ? FATAL : LOG,
122  (errmsg("could not create SSL context: %s",
123  SSLerrmessage(ERR_get_error()))));
124  goto error;
125  }
126 
127  /*
128  * Disable OpenSSL's moving-write-buffer sanity check, because it causes
129  * unnecessary failures in nonblocking send cases.
130  */
131  SSL_CTX_set_mode(context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
132 
133  /*
134  * Call init hook (usually to set password callback)
135  */
136  (*openssl_tls_init_hook) (context, isServerStart);
137 
138  /* used by the callback */
139  ssl_is_server_start = isServerStart;
140 
141  /*
142  * Load and verify server's certificate and private key
143  */
144  if (SSL_CTX_use_certificate_chain_file(context, ssl_cert_file) != 1)
145  {
146  ereport(isServerStart ? FATAL : LOG,
147  (errcode(ERRCODE_CONFIG_FILE_ERROR),
148  errmsg("could not load server certificate file \"%s\": %s",
149  ssl_cert_file, SSLerrmessage(ERR_get_error()))));
150  goto error;
151  }
152 
153  if (!check_ssl_key_file_permissions(ssl_key_file, isServerStart))
154  goto error;
155 
156  /*
157  * OK, try to load the private key file.
158  */
160 
161  if (SSL_CTX_use_PrivateKey_file(context,
162  ssl_key_file,
163  SSL_FILETYPE_PEM) != 1)
164  {
166  ereport(isServerStart ? FATAL : LOG,
167  (errcode(ERRCODE_CONFIG_FILE_ERROR),
168  errmsg("private key file \"%s\" cannot be reloaded because it requires a passphrase",
169  ssl_key_file)));
170  else
171  ereport(isServerStart ? FATAL : LOG,
172  (errcode(ERRCODE_CONFIG_FILE_ERROR),
173  errmsg("could not load private key file \"%s\": %s",
174  ssl_key_file, SSLerrmessage(ERR_get_error()))));
175  goto error;
176  }
177 
178  if (SSL_CTX_check_private_key(context) != 1)
179  {
180  ereport(isServerStart ? FATAL : LOG,
181  (errcode(ERRCODE_CONFIG_FILE_ERROR),
182  errmsg("check of private key failed: %s",
183  SSLerrmessage(ERR_get_error()))));
184  goto error;
185  }
186 
188  {
190 
191  if (ssl_ver_min == -1)
192  {
193  ereport(isServerStart ? FATAL : LOG,
194  /*- translator: first %s is a GUC option name, second %s is its value */
195  (errmsg("\"%s\" setting \"%s\" not supported by this build",
196  "ssl_min_protocol_version",
197  GetConfigOption("ssl_min_protocol_version",
198  false, false))));
199  goto error;
200  }
201 
202  if (!SSL_CTX_set_min_proto_version(context, ssl_ver_min))
203  {
204  ereport(isServerStart ? FATAL : LOG,
205  (errmsg("could not set minimum SSL protocol version")));
206  goto error;
207  }
208  }
209 
211  {
213 
214  if (ssl_ver_max == -1)
215  {
216  ereport(isServerStart ? FATAL : LOG,
217  /*- translator: first %s is a GUC option name, second %s is its value */
218  (errmsg("\"%s\" setting \"%s\" not supported by this build",
219  "ssl_max_protocol_version",
220  GetConfigOption("ssl_max_protocol_version",
221  false, false))));
222  goto error;
223  }
224 
225  if (!SSL_CTX_set_max_proto_version(context, ssl_ver_max))
226  {
227  ereport(isServerStart ? FATAL : LOG,
228  (errmsg("could not set maximum SSL protocol version")));
229  goto error;
230  }
231  }
232 
233  /* Check compatibility of min/max protocols */
236  {
237  /*
238  * No need to check for invalid values (-1) for each protocol number
239  * as the code above would have already generated an error.
240  */
241  if (ssl_ver_min > ssl_ver_max)
242  {
243  ereport(isServerStart ? FATAL : LOG,
244  (errmsg("could not set SSL protocol version range"),
245  errdetail("\"%s\" cannot be higher than \"%s\"",
246  "ssl_min_protocol_version",
247  "ssl_max_protocol_version")));
248  goto error;
249  }
250  }
251 
252  /* disallow SSL session tickets */
253  SSL_CTX_set_options(context, SSL_OP_NO_TICKET);
254 
255  /* disallow SSL session caching, too */
256  SSL_CTX_set_session_cache_mode(context, SSL_SESS_CACHE_OFF);
257 
258  /* disallow SSL compression */
259  SSL_CTX_set_options(context, SSL_OP_NO_COMPRESSION);
260 
261 #ifdef SSL_OP_NO_RENEGOTIATION
262 
263  /*
264  * Disallow SSL renegotiation, option available since 1.1.0h. This
265  * concerns only TLSv1.2 and older protocol versions, as TLSv1.3 has no
266  * support for renegotiation.
267  */
268  SSL_CTX_set_options(context, SSL_OP_NO_RENEGOTIATION);
269 #endif
270 
271  /* set up ephemeral DH and ECDH keys */
272  if (!initialize_dh(context, isServerStart))
273  goto error;
274  if (!initialize_ecdh(context, isServerStart))
275  goto error;
276 
277  /* set up the allowed cipher list */
278  if (SSL_CTX_set_cipher_list(context, SSLCipherSuites) != 1)
279  {
280  ereport(isServerStart ? FATAL : LOG,
281  (errcode(ERRCODE_CONFIG_FILE_ERROR),
282  errmsg("could not set the cipher list (no valid ciphers available)")));
283  goto error;
284  }
285 
286  /* Let server choose order */
288  SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
289 
290  /*
291  * Load CA store, so we can verify client certificates if needed.
292  */
293  if (ssl_ca_file[0])
294  {
295  STACK_OF(X509_NAME) * root_cert_list;
296 
297  if (SSL_CTX_load_verify_locations(context, ssl_ca_file, NULL) != 1 ||
298  (root_cert_list = SSL_load_client_CA_file(ssl_ca_file)) == NULL)
299  {
300  ereport(isServerStart ? FATAL : LOG,
301  (errcode(ERRCODE_CONFIG_FILE_ERROR),
302  errmsg("could not load root certificate file \"%s\": %s",
303  ssl_ca_file, SSLerrmessage(ERR_get_error()))));
304  goto error;
305  }
306 
307  /*
308  * Tell OpenSSL to send the list of root certs we trust to clients in
309  * CertificateRequests. This lets a client with a keystore select the
310  * appropriate client certificate to send to us. Also, this ensures
311  * that the SSL context will "own" the root_cert_list and remember to
312  * free it when no longer needed.
313  */
314  SSL_CTX_set_client_CA_list(context, root_cert_list);
315 
316  /*
317  * Always ask for SSL client cert, but don't fail if it's not
318  * presented. We might fail such connections later, depending on what
319  * we find in pg_hba.conf.
320  */
321  SSL_CTX_set_verify(context,
322  (SSL_VERIFY_PEER |
323  SSL_VERIFY_CLIENT_ONCE),
324  verify_cb);
325  }
326 
327  /*----------
328  * Load the Certificate Revocation List (CRL).
329  * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
330  *----------
331  */
332  if (ssl_crl_file[0] || ssl_crl_dir[0])
333  {
334  X509_STORE *cvstore = SSL_CTX_get_cert_store(context);
335 
336  if (cvstore)
337  {
338  /* Set the flags to check against the complete CRL chain */
339  if (X509_STORE_load_locations(cvstore,
340  ssl_crl_file[0] ? ssl_crl_file : NULL,
341  ssl_crl_dir[0] ? ssl_crl_dir : NULL)
342  == 1)
343  {
344  X509_STORE_set_flags(cvstore,
345  X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
346  }
347  else if (ssl_crl_dir[0] == 0)
348  {
349  ereport(isServerStart ? FATAL : LOG,
350  (errcode(ERRCODE_CONFIG_FILE_ERROR),
351  errmsg("could not load SSL certificate revocation list file \"%s\": %s",
352  ssl_crl_file, SSLerrmessage(ERR_get_error()))));
353  goto error;
354  }
355  else if (ssl_crl_file[0] == 0)
356  {
357  ereport(isServerStart ? FATAL : LOG,
358  (errcode(ERRCODE_CONFIG_FILE_ERROR),
359  errmsg("could not load SSL certificate revocation list directory \"%s\": %s",
360  ssl_crl_dir, SSLerrmessage(ERR_get_error()))));
361  goto error;
362  }
363  else
364  {
365  ereport(isServerStart ? FATAL : LOG,
366  (errcode(ERRCODE_CONFIG_FILE_ERROR),
367  errmsg("could not load SSL certificate revocation list file \"%s\" or directory \"%s\": %s",
369  SSLerrmessage(ERR_get_error()))));
370  goto error;
371  }
372  }
373  }
374 
375  /*
376  * Success! Replace any existing SSL_context.
377  */
378  if (SSL_context)
379  SSL_CTX_free(SSL_context);
380 
381  SSL_context = context;
382 
383  /*
384  * Set flag to remember whether CA store has been loaded into SSL_context.
385  */
386  if (ssl_ca_file[0])
387  ssl_loaded_verify_locations = true;
388  else
389  ssl_loaded_verify_locations = false;
390 
391  return 0;
392 
393  /* Clean up by releasing working context. */
394 error:
395  if (context)
396  SSL_CTX_free(context);
397  return -1;
398 }
399 
400 void
402 {
403  if (SSL_context)
404  SSL_CTX_free(SSL_context);
405  SSL_context = NULL;
406  ssl_loaded_verify_locations = false;
407 }
408 
409 int
411 {
412  int r;
413  int err;
414  int waitfor;
415  unsigned long ecode;
416  bool give_proto_hint;
417 
418  Assert(!port->ssl);
419  Assert(!port->peer);
420 
421  if (!SSL_context)
422  {
424  (errcode(ERRCODE_PROTOCOL_VIOLATION),
425  errmsg("could not initialize SSL connection: SSL context not set up")));
426  return -1;
427  }
428 
429  /* set up debugging/info callback */
430  SSL_CTX_set_info_callback(SSL_context, info_cb);
431 
432  if (!(port->ssl = SSL_new(SSL_context)))
433  {
435  (errcode(ERRCODE_PROTOCOL_VIOLATION),
436  errmsg("could not initialize SSL connection: %s",
437  SSLerrmessage(ERR_get_error()))));
438  return -1;
439  }
440  if (!my_SSL_set_fd(port, port->sock))
441  {
443  (errcode(ERRCODE_PROTOCOL_VIOLATION),
444  errmsg("could not set SSL socket: %s",
445  SSLerrmessage(ERR_get_error()))));
446  return -1;
447  }
448  port->ssl_in_use = true;
449 
450 aloop:
451 
452  /*
453  * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
454  * queue. In general, the current thread's error queue must be empty
455  * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
456  * not work reliably. An extension may have failed to clear the
457  * per-thread error queue following another call to an OpenSSL I/O
458  * routine.
459  */
460  ERR_clear_error();
461  r = SSL_accept(port->ssl);
462  if (r <= 0)
463  {
464  err = SSL_get_error(port->ssl, r);
465 
466  /*
467  * Other clients of OpenSSL in the backend may fail to call
468  * ERR_get_error(), but we always do, so as to not cause problems for
469  * OpenSSL clients that don't call ERR_clear_error() defensively. Be
470  * sure that this happens by calling now. SSL_get_error() relies on
471  * the OpenSSL per-thread error queue being intact, so this is the
472  * earliest possible point ERR_get_error() may be called.
473  */
474  ecode = ERR_get_error();
475  switch (err)
476  {
477  case SSL_ERROR_WANT_READ:
478  case SSL_ERROR_WANT_WRITE:
479  /* not allowed during connection establishment */
480  Assert(!port->noblock);
481 
482  /*
483  * No need to care about timeouts/interrupts here. At this
484  * point authentication_timeout still employs
485  * StartupPacketTimeoutHandler() which directly exits.
486  */
487  if (err == SSL_ERROR_WANT_READ)
489  else
491 
492  (void) WaitLatchOrSocket(MyLatch, waitfor, port->sock, 0,
494  goto aloop;
495  case SSL_ERROR_SYSCALL:
496  if (r < 0)
499  errmsg("could not accept SSL connection: %m")));
500  else
502  (errcode(ERRCODE_PROTOCOL_VIOLATION),
503  errmsg("could not accept SSL connection: EOF detected")));
504  break;
505  case SSL_ERROR_SSL:
506  switch (ERR_GET_REASON(ecode))
507  {
508  /*
509  * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
510  * TLSV1_ALERT_PROTOCOL_VERSION have been observed
511  * when trying to communicate with an old OpenSSL
512  * library, or when the client and server specify
513  * disjoint protocol ranges. NO_PROTOCOLS_AVAILABLE
514  * occurs if there's a local misconfiguration (which
515  * can happen despite our checks, if openssl.cnf
516  * injects a limit we didn't account for). It's not
517  * very clear what would make OpenSSL return the other
518  * codes listed here, but a hint about protocol
519  * versions seems like it's appropriate for all.
520  */
521  case SSL_R_NO_PROTOCOLS_AVAILABLE:
522  case SSL_R_UNSUPPORTED_PROTOCOL:
523  case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
524  case SSL_R_UNKNOWN_PROTOCOL:
525  case SSL_R_UNKNOWN_SSL_VERSION:
526  case SSL_R_UNSUPPORTED_SSL_VERSION:
527  case SSL_R_WRONG_SSL_VERSION:
528  case SSL_R_WRONG_VERSION_NUMBER:
529  case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
530 #ifdef SSL_R_VERSION_TOO_HIGH
531  case SSL_R_VERSION_TOO_HIGH:
532  case SSL_R_VERSION_TOO_LOW:
533 #endif
534  give_proto_hint = true;
535  break;
536  default:
537  give_proto_hint = false;
538  break;
539  }
541  (errcode(ERRCODE_PROTOCOL_VIOLATION),
542  errmsg("could not accept SSL connection: %s",
543  SSLerrmessage(ecode)),
544  give_proto_hint ?
545  errhint("This may indicate that the client does not support any SSL protocol version between %s and %s.",
548  MIN_OPENSSL_TLS_VERSION,
551  MAX_OPENSSL_TLS_VERSION) : 0));
552  break;
553  case SSL_ERROR_ZERO_RETURN:
555  (errcode(ERRCODE_PROTOCOL_VIOLATION),
556  errmsg("could not accept SSL connection: EOF detected")));
557  break;
558  default:
560  (errcode(ERRCODE_PROTOCOL_VIOLATION),
561  errmsg("unrecognized SSL error code: %d",
562  err)));
563  break;
564  }
565  return -1;
566  }
567 
568  /* Get client certificate, if available. */
569  port->peer = SSL_get_peer_certificate(port->ssl);
570 
571  /* and extract the Common Name and Distinguished Name from it. */
572  port->peer_cn = NULL;
573  port->peer_dn = NULL;
574  port->peer_cert_valid = false;
575  if (port->peer != NULL)
576  {
577  int len;
578  X509_NAME *x509name = X509_get_subject_name(port->peer);
579  char *peer_dn;
580  BIO *bio = NULL;
581  BUF_MEM *bio_buf = NULL;
582 
583  len = X509_NAME_get_text_by_NID(x509name, NID_commonName, NULL, 0);
584  if (len != -1)
585  {
586  char *peer_cn;
587 
588  peer_cn = MemoryContextAlloc(TopMemoryContext, len + 1);
589  r = X509_NAME_get_text_by_NID(x509name, NID_commonName, peer_cn,
590  len + 1);
591  peer_cn[len] = '\0';
592  if (r != len)
593  {
594  /* shouldn't happen */
595  pfree(peer_cn);
596  return -1;
597  }
598 
599  /*
600  * Reject embedded NULLs in certificate common name to prevent
601  * attacks like CVE-2009-4034.
602  */
603  if (len != strlen(peer_cn))
604  {
606  (errcode(ERRCODE_PROTOCOL_VIOLATION),
607  errmsg("SSL certificate's common name contains embedded null")));
608  pfree(peer_cn);
609  return -1;
610  }
611 
612  port->peer_cn = peer_cn;
613  }
614 
615  bio = BIO_new(BIO_s_mem());
616  if (!bio)
617  {
618  pfree(port->peer_cn);
619  port->peer_cn = NULL;
620  return -1;
621  }
622 
623  /*
624  * RFC2253 is the closest thing to an accepted standard format for
625  * DNs. We have documented how to produce this format from a
626  * certificate. It uses commas instead of slashes for delimiters,
627  * which make regular expression matching a bit easier. Also note that
628  * it prints the Subject fields in reverse order.
629  */
630  X509_NAME_print_ex(bio, x509name, 0, XN_FLAG_RFC2253);
631  if (BIO_get_mem_ptr(bio, &bio_buf) <= 0)
632  {
633  BIO_free(bio);
634  pfree(port->peer_cn);
635  port->peer_cn = NULL;
636  return -1;
637  }
638  peer_dn = MemoryContextAlloc(TopMemoryContext, bio_buf->length + 1);
639  memcpy(peer_dn, bio_buf->data, bio_buf->length);
640  len = bio_buf->length;
641  BIO_free(bio);
642  peer_dn[len] = '\0';
643  if (len != strlen(peer_dn))
644  {
646  (errcode(ERRCODE_PROTOCOL_VIOLATION),
647  errmsg("SSL certificate's distinguished name contains embedded null")));
648  pfree(peer_dn);
649  pfree(port->peer_cn);
650  port->peer_cn = NULL;
651  return -1;
652  }
653 
654  port->peer_dn = peer_dn;
655 
656  port->peer_cert_valid = true;
657  }
658 
659  return 0;
660 }
661 
662 void
664 {
665  if (port->ssl)
666  {
667  SSL_shutdown(port->ssl);
668  SSL_free(port->ssl);
669  port->ssl = NULL;
670  port->ssl_in_use = false;
671  }
672 
673  if (port->peer)
674  {
675  X509_free(port->peer);
676  port->peer = NULL;
677  }
678 
679  if (port->peer_cn)
680  {
681  pfree(port->peer_cn);
682  port->peer_cn = NULL;
683  }
684 
685  if (port->peer_dn)
686  {
687  pfree(port->peer_dn);
688  port->peer_dn = NULL;
689  }
690 }
691 
692 ssize_t
693 be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
694 {
695  ssize_t n;
696  int err;
697  unsigned long ecode;
698 
699  errno = 0;
700  ERR_clear_error();
701  n = SSL_read(port->ssl, ptr, len);
702  err = SSL_get_error(port->ssl, n);
703  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
704  switch (err)
705  {
706  case SSL_ERROR_NONE:
707  /* a-ok */
708  break;
709  case SSL_ERROR_WANT_READ:
710  *waitfor = WL_SOCKET_READABLE;
711  errno = EWOULDBLOCK;
712  n = -1;
713  break;
714  case SSL_ERROR_WANT_WRITE:
715  *waitfor = WL_SOCKET_WRITEABLE;
716  errno = EWOULDBLOCK;
717  n = -1;
718  break;
719  case SSL_ERROR_SYSCALL:
720  /* leave it to caller to ereport the value of errno */
721  if (n != -1)
722  {
723  errno = ECONNRESET;
724  n = -1;
725  }
726  break;
727  case SSL_ERROR_SSL:
729  (errcode(ERRCODE_PROTOCOL_VIOLATION),
730  errmsg("SSL error: %s", SSLerrmessage(ecode))));
731  errno = ECONNRESET;
732  n = -1;
733  break;
734  case SSL_ERROR_ZERO_RETURN:
735  /* connection was cleanly shut down by peer */
736  n = 0;
737  break;
738  default:
740  (errcode(ERRCODE_PROTOCOL_VIOLATION),
741  errmsg("unrecognized SSL error code: %d",
742  err)));
743  errno = ECONNRESET;
744  n = -1;
745  break;
746  }
747 
748  return n;
749 }
750 
751 ssize_t
752 be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
753 {
754  ssize_t n;
755  int err;
756  unsigned long ecode;
757 
758  errno = 0;
759  ERR_clear_error();
760  n = SSL_write(port->ssl, ptr, len);
761  err = SSL_get_error(port->ssl, n);
762  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
763  switch (err)
764  {
765  case SSL_ERROR_NONE:
766  /* a-ok */
767  break;
768  case SSL_ERROR_WANT_READ:
769  *waitfor = WL_SOCKET_READABLE;
770  errno = EWOULDBLOCK;
771  n = -1;
772  break;
773  case SSL_ERROR_WANT_WRITE:
774  *waitfor = WL_SOCKET_WRITEABLE;
775  errno = EWOULDBLOCK;
776  n = -1;
777  break;
778  case SSL_ERROR_SYSCALL:
779  /* leave it to caller to ereport the value of errno */
780  if (n != -1)
781  {
782  errno = ECONNRESET;
783  n = -1;
784  }
785  break;
786  case SSL_ERROR_SSL:
788  (errcode(ERRCODE_PROTOCOL_VIOLATION),
789  errmsg("SSL error: %s", SSLerrmessage(ecode))));
790  errno = ECONNRESET;
791  n = -1;
792  break;
793  case SSL_ERROR_ZERO_RETURN:
794 
795  /*
796  * the SSL connection was closed, leave it to the caller to
797  * ereport it
798  */
799  errno = ECONNRESET;
800  n = -1;
801  break;
802  default:
804  (errcode(ERRCODE_PROTOCOL_VIOLATION),
805  errmsg("unrecognized SSL error code: %d",
806  err)));
807  errno = ECONNRESET;
808  n = -1;
809  break;
810  }
811 
812  return n;
813 }
814 
815 /* ------------------------------------------------------------ */
816 /* Internal functions */
817 /* ------------------------------------------------------------ */
818 
819 /*
820  * Private substitute BIO: this does the sending and receiving using send() and
821  * recv() instead. This is so that we can enable and disable interrupts
822  * just while calling recv(). We cannot have interrupts occurring while
823  * the bulk of OpenSSL runs, because it uses malloc() and possibly other
824  * non-reentrant libc facilities. We also need to call send() and recv()
825  * directly so it gets passed through the socket/signals layer on Win32.
826  *
827  * These functions are closely modelled on the standard socket BIO in OpenSSL;
828  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
829  * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
830  * to retry; do we need to adopt their logic for that?
831  */
832 
833 #ifndef HAVE_BIO_GET_DATA
834 #define BIO_get_data(bio) (bio->ptr)
835 #define BIO_set_data(bio, data) (bio->ptr = data)
836 #endif
837 
838 static BIO_METHOD *my_bio_methods = NULL;
839 
840 static int
841 my_sock_read(BIO *h, char *buf, int size)
842 {
843  int res = 0;
844 
845  if (buf != NULL)
846  {
847  res = secure_raw_read(((Port *) BIO_get_data(h)), buf, size);
848  BIO_clear_retry_flags(h);
849  if (res <= 0)
850  {
851  /* If we were interrupted, tell caller to retry */
852  if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
853  {
854  BIO_set_retry_read(h);
855  }
856  }
857  }
858 
859  return res;
860 }
861 
862 static int
863 my_sock_write(BIO *h, const char *buf, int size)
864 {
865  int res = 0;
866 
867  res = secure_raw_write(((Port *) BIO_get_data(h)), buf, size);
868  BIO_clear_retry_flags(h);
869  if (res <= 0)
870  {
871  /* If we were interrupted, tell caller to retry */
872  if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
873  {
874  BIO_set_retry_write(h);
875  }
876  }
877 
878  return res;
879 }
880 
881 static BIO_METHOD *
883 {
884  if (!my_bio_methods)
885  {
886  BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
887 #ifdef HAVE_BIO_METH_NEW
888  int my_bio_index;
889 
890  my_bio_index = BIO_get_new_index();
891  if (my_bio_index == -1)
892  return NULL;
893  my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
894  my_bio_methods = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
895  if (!my_bio_methods)
896  return NULL;
897  if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
898  !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
899  !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
900  !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
901  !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
902  !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
903  !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
904  !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
905  {
906  BIO_meth_free(my_bio_methods);
907  my_bio_methods = NULL;
908  return NULL;
909  }
910 #else
911  my_bio_methods = malloc(sizeof(BIO_METHOD));
912  if (!my_bio_methods)
913  return NULL;
914  memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
915  my_bio_methods->bread = my_sock_read;
916  my_bio_methods->bwrite = my_sock_write;
917 #endif
918  }
919  return my_bio_methods;
920 }
921 
922 /* This should exactly match OpenSSL's SSL_set_fd except for using my BIO */
923 static int
925 {
926  int ret = 0;
927  BIO *bio;
928  BIO_METHOD *bio_method;
929 
930  bio_method = my_BIO_s_socket();
931  if (bio_method == NULL)
932  {
933  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
934  goto err;
935  }
936  bio = BIO_new(bio_method);
937 
938  if (bio == NULL)
939  {
940  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
941  goto err;
942  }
943  BIO_set_data(bio, port);
944 
945  BIO_set_fd(bio, fd, BIO_NOCLOSE);
946  SSL_set_bio(port->ssl, bio, bio);
947  ret = 1;
948 err:
949  return ret;
950 }
951 
952 /*
953  * Load precomputed DH parameters.
954  *
955  * To prevent "downgrade" attacks, we perform a number of checks
956  * to verify that the DBA-generated DH parameters file contains
957  * what we expect it to contain.
958  */
959 static DH *
960 load_dh_file(char *filename, bool isServerStart)
961 {
962  FILE *fp;
963  DH *dh = NULL;
964  int codes;
965 
966  /* attempt to open file. It's not an error if it doesn't exist. */
967  if ((fp = AllocateFile(filename, "r")) == NULL)
968  {
969  ereport(isServerStart ? FATAL : LOG,
971  errmsg("could not open DH parameters file \"%s\": %m",
972  filename)));
973  return NULL;
974  }
975 
976  dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
977  FreeFile(fp);
978 
979  if (dh == NULL)
980  {
981  ereport(isServerStart ? FATAL : LOG,
982  (errcode(ERRCODE_CONFIG_FILE_ERROR),
983  errmsg("could not load DH parameters file: %s",
984  SSLerrmessage(ERR_get_error()))));
985  return NULL;
986  }
987 
988  /* make sure the DH parameters are usable */
989  if (DH_check(dh, &codes) == 0)
990  {
991  ereport(isServerStart ? FATAL : LOG,
992  (errcode(ERRCODE_CONFIG_FILE_ERROR),
993  errmsg("invalid DH parameters: %s",
994  SSLerrmessage(ERR_get_error()))));
995  DH_free(dh);
996  return NULL;
997  }
998  if (codes & DH_CHECK_P_NOT_PRIME)
999  {
1000  ereport(isServerStart ? FATAL : LOG,
1001  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1002  errmsg("invalid DH parameters: p is not prime")));
1003  DH_free(dh);
1004  return NULL;
1005  }
1006  if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
1007  (codes & DH_CHECK_P_NOT_SAFE_PRIME))
1008  {
1009  ereport(isServerStart ? FATAL : LOG,
1010  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1011  errmsg("invalid DH parameters: neither suitable generator or safe prime")));
1012  DH_free(dh);
1013  return NULL;
1014  }
1015 
1016  return dh;
1017 }
1018 
1019 /*
1020  * Load hardcoded DH parameters.
1021  *
1022  * If DH parameters cannot be loaded from a specified file, we can load
1023  * the hardcoded DH parameters supplied with the backend to prevent
1024  * problems.
1025  */
1026 static DH *
1027 load_dh_buffer(const char *buffer, size_t len)
1028 {
1029  BIO *bio;
1030  DH *dh = NULL;
1031 
1032  bio = BIO_new_mem_buf(unconstify(char *, buffer), len);
1033  if (bio == NULL)
1034  return NULL;
1035  dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1036  if (dh == NULL)
1037  ereport(DEBUG2,
1038  (errmsg_internal("DH load buffer: %s",
1039  SSLerrmessage(ERR_get_error()))));
1040  BIO_free(bio);
1041 
1042  return dh;
1043 }
1044 
1045 /*
1046  * Passphrase collection callback using ssl_passphrase_command
1047  */
1048 static int
1049 ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1050 {
1051  /* same prompt as OpenSSL uses internally */
1052  const char *prompt = "Enter PEM pass phrase:";
1053 
1054  Assert(rwflag == 0);
1055 
1056  return run_ssl_passphrase_command(prompt, ssl_is_server_start, buf, size);
1057 }
1058 
1059 /*
1060  * Dummy passphrase callback
1061  *
1062  * If OpenSSL is told to use a passphrase-protected server key, by default
1063  * it will issue a prompt on /dev/tty and try to read a key from there.
1064  * That's no good during a postmaster SIGHUP cycle, not to mention SSL context
1065  * reload in an EXEC_BACKEND postmaster child. So override it with this dummy
1066  * function that just returns an empty passphrase, guaranteeing failure.
1067  */
1068 static int
1069 dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
1070 {
1071  /* Set flag to change the error message we'll report */
1073  /* And return empty string */
1074  Assert(size > 0);
1075  buf[0] = '\0';
1076  return 0;
1077 }
1078 
1079 /*
1080  * Certificate verification callback
1081  *
1082  * This callback allows us to log intermediate problems during
1083  * verification, but for now we'll see if the final error message
1084  * contains enough information.
1085  *
1086  * This callback also allows us to override the default acceptance
1087  * criteria (e.g., accepting self-signed or expired certs), but
1088  * for now we accept the default checks.
1089  */
1090 static int
1091 verify_cb(int ok, X509_STORE_CTX *ctx)
1092 {
1093  return ok;
1094 }
1095 
1096 /*
1097  * This callback is used to copy SSL information messages
1098  * into the PostgreSQL log.
1099  */
1100 static void
1101 info_cb(const SSL *ssl, int type, int args)
1102 {
1103  const char *desc;
1104 
1105  desc = SSL_state_string_long(ssl);
1106 
1107  switch (type)
1108  {
1109  case SSL_CB_HANDSHAKE_START:
1110  ereport(DEBUG4,
1111  (errmsg_internal("SSL: handshake start: \"%s\"", desc)));
1112  break;
1113  case SSL_CB_HANDSHAKE_DONE:
1114  ereport(DEBUG4,
1115  (errmsg_internal("SSL: handshake done: \"%s\"", desc)));
1116  break;
1117  case SSL_CB_ACCEPT_LOOP:
1118  ereport(DEBUG4,
1119  (errmsg_internal("SSL: accept loop: \"%s\"", desc)));
1120  break;
1121  case SSL_CB_ACCEPT_EXIT:
1122  ereport(DEBUG4,
1123  (errmsg_internal("SSL: accept exit (%d): \"%s\"", args, desc)));
1124  break;
1125  case SSL_CB_CONNECT_LOOP:
1126  ereport(DEBUG4,
1127  (errmsg_internal("SSL: connect loop: \"%s\"", desc)));
1128  break;
1129  case SSL_CB_CONNECT_EXIT:
1130  ereport(DEBUG4,
1131  (errmsg_internal("SSL: connect exit (%d): \"%s\"", args, desc)));
1132  break;
1133  case SSL_CB_READ_ALERT:
1134  ereport(DEBUG4,
1135  (errmsg_internal("SSL: read alert (0x%04x): \"%s\"", args, desc)));
1136  break;
1137  case SSL_CB_WRITE_ALERT:
1138  ereport(DEBUG4,
1139  (errmsg_internal("SSL: write alert (0x%04x): \"%s\"", args, desc)));
1140  break;
1141  }
1142 }
1143 
1144 /*
1145  * Set DH parameters for generating ephemeral DH keys. The
1146  * DH parameters can take a long time to compute, so they must be
1147  * precomputed.
1148  *
1149  * Since few sites will bother to create a parameter file, we also
1150  * provide a fallback to the parameters provided by the OpenSSL
1151  * project.
1152  *
1153  * These values can be static (once loaded or computed) since the
1154  * OpenSSL library can efficiently generate random keys from the
1155  * information provided.
1156  */
1157 static bool
1158 initialize_dh(SSL_CTX *context, bool isServerStart)
1159 {
1160  DH *dh = NULL;
1161 
1162  SSL_CTX_set_options(context, SSL_OP_SINGLE_DH_USE);
1163 
1164  if (ssl_dh_params_file[0])
1165  dh = load_dh_file(ssl_dh_params_file, isServerStart);
1166  if (!dh)
1167  dh = load_dh_buffer(FILE_DH2048, sizeof(FILE_DH2048));
1168  if (!dh)
1169  {
1170  ereport(isServerStart ? FATAL : LOG,
1171  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1172  errmsg("DH: could not load DH parameters")));
1173  return false;
1174  }
1175 
1176  if (SSL_CTX_set_tmp_dh(context, dh) != 1)
1177  {
1178  ereport(isServerStart ? FATAL : LOG,
1179  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1180  errmsg("DH: could not set DH parameters: %s",
1181  SSLerrmessage(ERR_get_error()))));
1182  DH_free(dh);
1183  return false;
1184  }
1185 
1186  DH_free(dh);
1187  return true;
1188 }
1189 
1190 /*
1191  * Set ECDH parameters for generating ephemeral Elliptic Curve DH
1192  * keys. This is much simpler than the DH parameters, as we just
1193  * need to provide the name of the curve to OpenSSL.
1194  */
1195 static bool
1196 initialize_ecdh(SSL_CTX *context, bool isServerStart)
1197 {
1198 #ifndef OPENSSL_NO_ECDH
1199  EC_KEY *ecdh;
1200  int nid;
1201 
1202  nid = OBJ_sn2nid(SSLECDHCurve);
1203  if (!nid)
1204  {
1205  ereport(isServerStart ? FATAL : LOG,
1206  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1207  errmsg("ECDH: unrecognized curve name: %s", SSLECDHCurve)));
1208  return false;
1209  }
1210 
1211  ecdh = EC_KEY_new_by_curve_name(nid);
1212  if (!ecdh)
1213  {
1214  ereport(isServerStart ? FATAL : LOG,
1215  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1216  errmsg("ECDH: could not create key")));
1217  return false;
1218  }
1219 
1220  SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
1221  SSL_CTX_set_tmp_ecdh(context, ecdh);
1222  EC_KEY_free(ecdh);
1223 #endif
1224 
1225  return true;
1226 }
1227 
1228 /*
1229  * Obtain reason string for passed SSL errcode
1230  *
1231  * ERR_get_error() is used by caller to get errcode to pass here.
1232  *
1233  * Some caution is needed here since ERR_reason_error_string will
1234  * return NULL if it doesn't recognize the error code. We don't
1235  * want to return NULL ever.
1236  */
1237 static const char *
1238 SSLerrmessage(unsigned long ecode)
1239 {
1240  const char *errreason;
1241  static char errbuf[36];
1242 
1243  if (ecode == 0)
1244  return _("no SSL error reported");
1245  errreason = ERR_reason_error_string(ecode);
1246  if (errreason != NULL)
1247  return errreason;
1248  snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), ecode);
1249  return errbuf;
1250 }
1251 
1252 int
1254 {
1255  int bits;
1256 
1257  if (port->ssl)
1258  {
1259  SSL_get_cipher_bits(port->ssl, &bits);
1260  return bits;
1261  }
1262  else
1263  return 0;
1264 }
1265 
1266 const char *
1268 {
1269  if (port->ssl)
1270  return SSL_get_version(port->ssl);
1271  else
1272  return NULL;
1273 }
1274 
1275 const char *
1277 {
1278  if (port->ssl)
1279  return SSL_get_cipher(port->ssl);
1280  else
1281  return NULL;
1282 }
1283 
1284 void
1286 {
1287  if (port->peer)
1288  strlcpy(ptr, X509_NAME_to_cstring(X509_get_subject_name(port->peer)), len);
1289  else
1290  ptr[0] = '\0';
1291 }
1292 
1293 void
1295 {
1296  if (port->peer)
1297  strlcpy(ptr, X509_NAME_to_cstring(X509_get_issuer_name(port->peer)), len);
1298  else
1299  ptr[0] = '\0';
1300 }
1301 
1302 void
1303 be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
1304 {
1305  if (port->peer)
1306  {
1307  ASN1_INTEGER *serial;
1308  BIGNUM *b;
1309  char *decimal;
1310 
1311  serial = X509_get_serialNumber(port->peer);
1312  b = ASN1_INTEGER_to_BN(serial, NULL);
1313  decimal = BN_bn2dec(b);
1314 
1315  BN_free(b);
1316  strlcpy(ptr, decimal, len);
1317  OPENSSL_free(decimal);
1318  }
1319  else
1320  ptr[0] = '\0';
1321 }
1322 
1323 #ifdef HAVE_X509_GET_SIGNATURE_NID
1324 char *
1325 be_tls_get_certificate_hash(Port *port, size_t *len)
1326 {
1327  X509 *server_cert;
1328  char *cert_hash;
1329  const EVP_MD *algo_type = NULL;
1330  unsigned char hash[EVP_MAX_MD_SIZE]; /* size for SHA-512 */
1331  unsigned int hash_size;
1332  int algo_nid;
1333 
1334  *len = 0;
1335  server_cert = SSL_get_certificate(port->ssl);
1336  if (server_cert == NULL)
1337  return NULL;
1338 
1339  /*
1340  * Get the signature algorithm of the certificate to determine the hash
1341  * algorithm to use for the result.
1342  */
1343  if (!OBJ_find_sigid_algs(X509_get_signature_nid(server_cert),
1344  &algo_nid, NULL))
1345  elog(ERROR, "could not determine server certificate signature algorithm");
1346 
1347  /*
1348  * The TLS server's certificate bytes need to be hashed with SHA-256 if
1349  * its signature algorithm is MD5 or SHA-1 as per RFC 5929
1350  * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
1351  * is used, the same hash as the signature algorithm is used.
1352  */
1353  switch (algo_nid)
1354  {
1355  case NID_md5:
1356  case NID_sha1:
1357  algo_type = EVP_sha256();
1358  break;
1359  default:
1360  algo_type = EVP_get_digestbynid(algo_nid);
1361  if (algo_type == NULL)
1362  elog(ERROR, "could not find digest for NID %s",
1363  OBJ_nid2sn(algo_nid));
1364  break;
1365  }
1366 
1367  /* generate and save the certificate hash */
1368  if (!X509_digest(server_cert, algo_type, hash, &hash_size))
1369  elog(ERROR, "could not generate server certificate hash");
1370 
1371  cert_hash = palloc(hash_size);
1372  memcpy(cert_hash, hash, hash_size);
1373  *len = hash_size;
1374 
1375  return cert_hash;
1376 }
1377 #endif
1378 
1379 /*
1380  * Convert an X509 subject name to a cstring.
1381  *
1382  */
1383 static char *
1385 {
1386  BIO *membuf = BIO_new(BIO_s_mem());
1387  int i,
1388  nid,
1389  count = X509_NAME_entry_count(name);
1390  X509_NAME_ENTRY *e;
1391  ASN1_STRING *v;
1392  const char *field_name;
1393  size_t size;
1394  char nullterm;
1395  char *sp;
1396  char *dp;
1397  char *result;
1398 
1399  if (membuf == NULL)
1400  ereport(ERROR,
1401  (errcode(ERRCODE_OUT_OF_MEMORY),
1402  errmsg("could not create BIO")));
1403 
1404  (void) BIO_set_close(membuf, BIO_CLOSE);
1405  for (i = 0; i < count; i++)
1406  {
1407  e = X509_NAME_get_entry(name, i);
1408  nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(e));
1409  if (nid == NID_undef)
1410  ereport(ERROR,
1411  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1412  errmsg("could not get NID for ASN1_OBJECT object")));
1413  v = X509_NAME_ENTRY_get_data(e);
1414  field_name = OBJ_nid2sn(nid);
1415  if (field_name == NULL)
1416  field_name = OBJ_nid2ln(nid);
1417  if (field_name == NULL)
1418  ereport(ERROR,
1419  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1420  errmsg("could not convert NID %d to an ASN1_OBJECT structure", nid)));
1421  BIO_printf(membuf, "/%s=", field_name);
1422  ASN1_STRING_print_ex(membuf, v,
1423  ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
1424  | ASN1_STRFLGS_UTF8_CONVERT));
1425  }
1426 
1427  /* ensure null termination of the BIO's content */
1428  nullterm = '\0';
1429  BIO_write(membuf, &nullterm, 1);
1430  size = BIO_get_mem_data(membuf, &sp);
1431  dp = pg_any_to_server(sp, size - 1, PG_UTF8);
1432 
1433  result = pstrdup(dp);
1434  if (dp != sp)
1435  pfree(dp);
1436  if (BIO_free(membuf) != 1)
1437  elog(ERROR, "could not free OpenSSL BIO structure");
1438 
1439  return result;
1440 }
1441 
1442 /*
1443  * Convert TLS protocol version GUC enum to OpenSSL values
1444  *
1445  * This is a straightforward one-to-one mapping, but doing it this way makes
1446  * guc.c independent of OpenSSL availability and version.
1447  *
1448  * If a version is passed that is not supported by the current OpenSSL
1449  * version, then we return -1. If a nonnegative value is returned,
1450  * subsequent code can assume it's working with a supported version.
1451  *
1452  * Note: this is rather similar to libpq's routine in fe-secure-openssl.c,
1453  * so make sure to update both routines if changing this one.
1454  */
1455 static int
1457 {
1458  switch (v)
1459  {
1460  case PG_TLS_ANY:
1461  return 0;
1462  case PG_TLS1_VERSION:
1463  return TLS1_VERSION;
1464  case PG_TLS1_1_VERSION:
1465 #ifdef TLS1_1_VERSION
1466  return TLS1_1_VERSION;
1467 #else
1468  break;
1469 #endif
1470  case PG_TLS1_2_VERSION:
1471 #ifdef TLS1_2_VERSION
1472  return TLS1_2_VERSION;
1473 #else
1474  break;
1475 #endif
1476  case PG_TLS1_3_VERSION:
1477 #ifdef TLS1_3_VERSION
1478  return TLS1_3_VERSION;
1479 #else
1480  break;
1481 #endif
1482  }
1483 
1484  return -1;
1485 }
1486 
1487 /*
1488  * Likewise provide a mapping to strings.
1489  */
1490 static const char *
1492 {
1493  switch (v)
1494  {
1495  case PG_TLS_ANY:
1496  return "any";
1497  case PG_TLS1_VERSION:
1498  return "TLSv1";
1499  case PG_TLS1_1_VERSION:
1500  return "TLSv1.1";
1501  case PG_TLS1_2_VERSION:
1502  return "TLSv1.2";
1503  case PG_TLS1_3_VERSION:
1504  return "TLSv1.3";
1505  }
1506 
1507  return "(unrecognized)";
1508 }
1509 
1510 
1511 static void
1512 default_openssl_tls_init(SSL_CTX *context, bool isServerStart)
1513 {
1514  if (isServerStart)
1515  {
1516  if (ssl_passphrase_command[0])
1517  SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
1518  }
1519  else
1520  {
1522  SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
1523  else
1524 
1525  /*
1526  * If reloading and no external command is configured, override
1527  * OpenSSL's default handling of passphrase-protected files,
1528  * because we don't want to prompt for a passphrase in an
1529  * already-running server.
1530  */
1531  SSL_CTX_set_default_passwd_cb(context, dummy_ssl_passwd_cb);
1532  }
1533 }
bool check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
int run_ssl_passphrase_command(const char *prompt, bool is_server_start, char *buf, int size)
static const char * ssl_protocol_version_to_string(int v)
const char * be_tls_get_version(Port *port)
static DH * load_dh_buffer(const char *, size_t)
static void info_cb(const SSL *ssl, int type, int args)
static const char * SSLerrmessage(unsigned long ecode)
void be_tls_destroy(void)
int be_tls_init(bool isServerStart)
openssl_tls_init_hook_typ openssl_tls_init_hook
int be_tls_get_cipher_bits(Port *port)
int be_tls_open_server(Port *port)
static BIO_METHOD * my_bio_methods
static int dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
static int my_SSL_set_fd(Port *port, int fd)
static int verify_cb(int, X509_STORE_CTX *)
static void default_openssl_tls_init(SSL_CTX *context, bool isServerStart)
void be_tls_get_peer_serial(Port *port, char *ptr, size_t len)
#define BIO_get_data(bio)
static int ssl_protocol_version_to_openssl(int v)
static BIO_METHOD * my_BIO_s_socket(void)
static bool initialize_dh(SSL_CTX *context, bool isServerStart)
void be_tls_close(Port *port)
void be_tls_get_peer_issuer_name(Port *port, char *ptr, size_t len)
#define BIO_set_data(bio, data)
ssize_t be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
static char * X509_NAME_to_cstring(X509_NAME *name)
ssize_t be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
static int ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata)
static SSL_CTX * SSL_context
static bool ssl_is_server_start
const char * be_tls_get_cipher(Port *port)
static bool SSL_initialized
static bool initialize_ecdh(SSL_CTX *context, bool isServerStart)
static bool dummy_ssl_passwd_cb_called
static DH * load_dh_file(char *filename, bool isServerStart)
static int my_sock_write(BIO *h, const char *buf, int size)
void be_tls_get_peer_subject_name(Port *port, char *ptr, size_t len)
static int my_sock_read(BIO *h, char *buf, int size)
char * ssl_crl_dir
Definition: be-secure.c:45
char * ssl_dh_params_file
Definition: be-secure.c:46
int ssl_min_protocol_version
Definition: be-secure.c:63
ssize_t secure_raw_read(Port *port, void *ptr, size_t len)
Definition: be-secure.c:236
char * ssl_cert_file
Definition: be-secure.c:41
bool SSLPreferServerCiphers
Definition: be-secure.c:61
int ssl_max_protocol_version
Definition: be-secure.c:64
char * ssl_passphrase_command
Definition: be-secure.c:47
bool ssl_passphrase_command_supports_reload
Definition: be-secure.c:48
char * SSLCipherSuites
Definition: be-secure.c:55
char * SSLECDHCurve
Definition: be-secure.c:58
char * ssl_key_file
Definition: be-secure.c:42
ssize_t secure_raw_write(Port *port, const void *ptr, size_t len)
Definition: be-secure.c:332
char * ssl_crl_file
Definition: be-secure.c:44
char * ssl_ca_file
Definition: be-secure.c:43
#define unconstify(underlying_type, expr)
Definition: c.h:1240
int errcode_for_socket_access(void)
Definition: elog.c:787
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
int errcode_for_file_access(void)
Definition: elog.c:716
int errdetail(const char *fmt,...)
Definition: elog.c:1037
int errhint(const char *fmt,...)
Definition: elog.c:1151
int errcode(int sqlerrcode)
Definition: elog.c:693
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define _(x)
Definition: elog.c:89
#define LOG
Definition: elog.h:25
#define COMMERROR
Definition: elog.h:27
#define FATAL
Definition: elog.h:35
#define DEBUG2
Definition: elog.h:23
#define ERROR
Definition: elog.h:33
#define elog(elevel,...)
Definition: elog.h:218
#define ereport(elevel,...)
Definition: elog.h:143
#define DEBUG4
Definition: elog.h:21
const char * name
Definition: encode.c:561
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2461
int FreeFile(FILE *file)
Definition: fd.c:2660
struct Latch * MyLatch
Definition: globals.c:57
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:8165
#define malloc(a)
Definition: header.h:50
int b
Definition: isn.c:70
int i
Definition: isn.c:73
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:500
#define WL_SOCKET_READABLE
Definition: latch.h:126
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_SOCKET_WRITEABLE
Definition: latch.h:127
@ PG_TLS1_VERSION
Definition: libpq.h:129
@ PG_TLS1_3_VERSION
Definition: libpq.h:132
@ PG_TLS1_1_VERSION
Definition: libpq.h:130
@ PG_TLS1_2_VERSION
Definition: libpq.h:131
@ PG_TLS_ANY
Definition: libpq.h:128
Assert(fmt[strlen(fmt) - 1] !='\n')
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:676
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void pfree(void *pointer)
Definition: mcxt.c:1169
MemoryContext TopMemoryContext
Definition: mcxt.c:48
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
void * palloc(Size size)
Definition: mcxt.c:1062
const void size_t len
static char * filename
Definition: pg_dumpall.c:92
static int port
Definition: pg_regress.c:92
static char * buf
Definition: pg_test_fsync.c:70
@ PG_UTF8
Definition: pg_wchar.h:230
#define snprintf
Definition: port.h:225
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
e
Definition: preproc-init.c:82
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)
static unsigned hash(unsigned *uv, int n)
Definition: rege_dfa.c:715
static void error(void)
Definition: sql-dyntest.c:147
Definition: libpq-be.h:126
@ WAIT_EVENT_SSL_OPEN_SERVER
Definition: wait_event.h:68
#define EINTR
Definition: win32_port.h:351
#define EWOULDBLOCK
Definition: win32_port.h:357
#define ECONNRESET
Definition: win32_port.h:361
#define EAGAIN
Definition: win32_port.h:349