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