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