PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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-2017, 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  * Since the server static private key ($DataDir/server.key)
15  * will normally be stored unencrypted so that the database
16  * backend can restart automatically, it is important that
17  * we select an algorithm that continues to provide confidentiality
18  * even if the attacker has the server's private key. Ephemeral
19  * DH (EDH) keys provide this and more (Perfect Forward Secrecy
20  * aka PFS).
21  *
22  * N.B., the static private key should still be protected to
23  * the largest extent possible, to minimize the risk of
24  * impersonations.
25  *
26  * Another benefit of EDH is that it allows the backend and
27  * clients to use DSA keys. DSA keys can only provide digital
28  * signatures, not encryption, and are often acceptable in
29  * jurisdictions where RSA keys are unacceptable.
30  *
31  * The downside to EDH is that it makes it impossible to
32  * use ssldump(1) if there's a problem establishing an SSL
33  * session. In this case you'll need to temporarily disable
34  * EDH by commenting out the callback.
35  *
36  *-------------------------------------------------------------------------
37  */
38 
39 #include "postgres.h"
40 
41 #include <sys/stat.h>
42 #include <signal.h>
43 #include <fcntl.h>
44 #include <ctype.h>
45 #include <sys/socket.h>
46 #include <unistd.h>
47 #include <netdb.h>
48 #include <netinet/in.h>
49 #ifdef HAVE_NETINET_TCP_H
50 #include <netinet/tcp.h>
51 #include <arpa/inet.h>
52 #endif
53 
54 #include <openssl/ssl.h>
55 #include <openssl/dh.h>
56 #include <openssl/conf.h>
57 #ifndef OPENSSL_NO_ECDH
58 #include <openssl/ec.h>
59 #endif
60 
61 #include "libpq/libpq.h"
62 #include "miscadmin.h"
63 #include "pgstat.h"
64 #include "storage/fd.h"
65 #include "storage/latch.h"
66 #include "tcop/tcopprot.h"
67 #include "utils/memutils.h"
68 
69 
70 static int my_sock_read(BIO *h, char *buf, int size);
71 static int my_sock_write(BIO *h, const char *buf, int size);
72 static BIO_METHOD *my_BIO_s_socket(void);
73 static int my_SSL_set_fd(Port *port, int fd);
74 
75 static DH *load_dh_file(char *filename, bool isServerStart);
76 static DH *load_dh_buffer(const char *, size_t);
77 static int ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata);
78 static int verify_cb(int, X509_STORE_CTX *);
79 static void info_cb(const SSL *ssl, int type, int args);
80 static bool initialize_dh(SSL_CTX *context, bool isServerStart);
81 static bool initialize_ecdh(SSL_CTX *context, bool isServerStart);
82 static const char *SSLerrmessage(unsigned long ecode);
83 
84 static char *X509_NAME_to_cstring(X509_NAME *name);
85 
86 static SSL_CTX *SSL_context = NULL;
87 static bool SSL_initialized = false;
88 static bool ssl_passwd_cb_called = false;
89 
90 /* ------------------------------------------------------------ */
91 /* Hardcoded values */
92 /* ------------------------------------------------------------ */
93 
94 /*
95  * Hardcoded DH parameters, used in ephemeral DH keying.
96  * As discussed above, EDH protects the confidentiality of
97  * sessions even if the static private key is compromised,
98  * so we are *highly* motivated to ensure that we can use
99  * EDH even if the DBA has not provided custom DH parameters.
100  *
101  * We could refuse SSL connections unless a good DH parameter
102  * file exists, but some clients may quietly renegotiate an
103  * unsecured connection without fully informing the user.
104  * Very uncool. Alternatively, the system could refuse to start
105  * if a DH parameters is not specified, but this would tend to
106  * piss off DBAs.
107  *
108  * If you want to create your own hardcoded DH parameters
109  * for fun and profit, review "Assigned Number for SKIP
110  * Protocols" (http://www.skip-vpn.org/spec/numbers.html)
111  * for suggestions.
112  */
113 
114 static const char file_dh2048[] =
115 "-----BEGIN DH PARAMETERS-----\n\
116 MIIBCAKCAQEA9kJXtwh/CBdyorrWqULzBej5UxE5T7bxbrlLOCDaAadWoxTpj0BV\n\
117 89AHxstDqZSt90xkhkn4DIO9ZekX1KHTUPj1WV/cdlJPPT2N286Z4VeSWc39uK50\n\
118 T8X8dryDxUcwYc58yWb/Ffm7/ZFexwGq01uejaClcjrUGvC/RgBYK+X0iP1YTknb\n\
119 zSC0neSRBzZrM2w4DUUdD3yIsxx8Wy2O9vPJI8BD8KVbGI2Ou1WMuF040zT9fBdX\n\
120 Q6MdGGzeMyEstSr/POGxKUAYEY18hKcKctaGxAMZyAcpesqVDNmWn6vQClCbAkbT\n\
121 CD1mpF1Bn5x8vYlLIhkmuquiXsNV6TILOwIBAg==\n\
122 -----END DH PARAMETERS-----\n";
123 
124 
125 /* ------------------------------------------------------------ */
126 /* Public interface */
127 /* ------------------------------------------------------------ */
128 
129 /*
130  * Initialize global SSL context.
131  *
132  * If isServerStart is true, report any errors as FATAL (so we don't return).
133  * Otherwise, log errors at LOG level and return -1 to indicate trouble,
134  * preserving the old SSL state if any. Returns 0 if OK.
135  */
136 int
137 be_tls_init(bool isServerStart)
138 {
139  STACK_OF(X509_NAME) *root_cert_list = NULL;
140  SSL_CTX *context;
141  struct stat buf;
142 
143  /* This stuff need be done only once. */
144  if (!SSL_initialized)
145  {
146 #ifdef HAVE_OPENSSL_INIT_SSL
147  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
148 #else
149  OPENSSL_config(NULL);
150  SSL_library_init();
151  SSL_load_error_strings();
152 #endif
153  SSL_initialized = true;
154  }
155 
156  /*
157  * We use SSLv23_method() because it can negotiate use of the highest
158  * mutually supported protocol version, while alternatives like
159  * TLSv1_2_method() permit only one specific version. Note that we don't
160  * actually allow SSL v2 or v3, only TLS protocols (see below).
161  */
162  context = SSL_CTX_new(SSLv23_method());
163  if (!context)
164  {
165  ereport(isServerStart ? FATAL : LOG,
166  (errmsg("could not create SSL context: %s",
167  SSLerrmessage(ERR_get_error()))));
168  goto error;
169  }
170 
171  /*
172  * Disable OpenSSL's moving-write-buffer sanity check, because it causes
173  * unnecessary failures in nonblocking send cases.
174  */
175  SSL_CTX_set_mode(context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
176 
177  /*
178  * If reloading, override OpenSSL's default handling of
179  * passphrase-protected files, because we don't want to prompt for a
180  * passphrase in an already-running server. (Not that the default
181  * handling is very desirable during server start either, but some people
182  * insist we need to keep it.)
183  */
184  if (!isServerStart)
185  SSL_CTX_set_default_passwd_cb(context, ssl_passwd_cb);
186 
187  /*
188  * Load and verify server's certificate and private key
189  */
190  if (SSL_CTX_use_certificate_chain_file(context, ssl_cert_file) != 1)
191  {
192  ereport(isServerStart ? FATAL : LOG,
193  (errcode(ERRCODE_CONFIG_FILE_ERROR),
194  errmsg("could not load server certificate file \"%s\": %s",
195  ssl_cert_file, SSLerrmessage(ERR_get_error()))));
196  goto error;
197  }
198 
199  if (stat(ssl_key_file, &buf) != 0)
200  {
201  ereport(isServerStart ? FATAL : LOG,
203  errmsg("could not access private key file \"%s\": %m",
204  ssl_key_file)));
205  goto error;
206  }
207 
208  if (!S_ISREG(buf.st_mode))
209  {
210  ereport(isServerStart ? FATAL : LOG,
211  (errcode(ERRCODE_CONFIG_FILE_ERROR),
212  errmsg("private key file \"%s\" is not a regular file",
213  ssl_key_file)));
214  goto error;
215  }
216 
217  /*
218  * Refuse to load key files owned by users other than us or root.
219  *
220  * XXX surely we can check this on Windows somehow, too.
221  */
222 #if !defined(WIN32) && !defined(__CYGWIN__)
223  if (buf.st_uid != geteuid() && buf.st_uid != 0)
224  {
225  ereport(isServerStart ? FATAL : LOG,
226  (errcode(ERRCODE_CONFIG_FILE_ERROR),
227  errmsg("private key file \"%s\" must be owned by the database user or root",
228  ssl_key_file)));
229  goto error;
230  }
231 #endif
232 
233  /*
234  * Require no public access to key file. If the file is owned by us,
235  * require mode 0600 or less. If owned by root, require 0640 or less to
236  * allow read access through our gid, or a supplementary gid that allows
237  * to read system-wide certificates.
238  *
239  * XXX temporarily suppress check when on Windows, because there may not
240  * be proper support for Unix-y file permissions. Need to think of a
241  * reasonable check to apply on Windows. (See also the data directory
242  * permission check in postmaster.c)
243  */
244 #if !defined(WIN32) && !defined(__CYGWIN__)
245  if ((buf.st_uid == geteuid() && buf.st_mode & (S_IRWXG | S_IRWXO)) ||
246  (buf.st_uid == 0 && buf.st_mode & (S_IWGRP | S_IXGRP | S_IRWXO)))
247  {
248  ereport(isServerStart ? FATAL : LOG,
249  (errcode(ERRCODE_CONFIG_FILE_ERROR),
250  errmsg("private key file \"%s\" has group or world access",
251  ssl_key_file),
252  errdetail("File must have permissions u=rw (0600) or less if owned by the database user, or permissions u=rw,g=r (0640) or less if owned by root.")));
253  goto error;
254  }
255 #endif
256 
257  /*
258  * OK, try to load the private key file.
259  */
260  ssl_passwd_cb_called = false;
261 
262  if (SSL_CTX_use_PrivateKey_file(context,
263  ssl_key_file,
264  SSL_FILETYPE_PEM) != 1)
265  {
267  ereport(isServerStart ? FATAL : LOG,
268  (errcode(ERRCODE_CONFIG_FILE_ERROR),
269  errmsg("private key file \"%s\" cannot be reloaded because it requires a passphrase",
270  ssl_key_file)));
271  else
272  ereport(isServerStart ? FATAL : LOG,
273  (errcode(ERRCODE_CONFIG_FILE_ERROR),
274  errmsg("could not load private key file \"%s\": %s",
275  ssl_key_file, SSLerrmessage(ERR_get_error()))));
276  goto error;
277  }
278 
279  if (SSL_CTX_check_private_key(context) != 1)
280  {
281  ereport(isServerStart ? FATAL : LOG,
282  (errcode(ERRCODE_CONFIG_FILE_ERROR),
283  errmsg("check of private key failed: %s",
284  SSLerrmessage(ERR_get_error()))));
285  goto error;
286  }
287 
288  /* disallow SSL v2/v3 */
289  SSL_CTX_set_options(context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
290 
291  /* disallow SSL session tickets */
292 #ifdef SSL_OP_NO_TICKET /* added in openssl 0.9.8f */
293  SSL_CTX_set_options(context, SSL_OP_NO_TICKET);
294 #endif
295 
296  /* disallow SSL session caching, too */
297  SSL_CTX_set_session_cache_mode(context, SSL_SESS_CACHE_OFF);
298 
299  /* set up ephemeral DH and ECDH keys */
300  if (!initialize_dh(context, isServerStart))
301  goto error;
302  if (!initialize_ecdh(context, isServerStart))
303  goto error;
304 
305  /* set up the allowed cipher list */
306  if (SSL_CTX_set_cipher_list(context, SSLCipherSuites) != 1)
307  {
308  ereport(isServerStart ? FATAL : LOG,
309  (errcode(ERRCODE_CONFIG_FILE_ERROR),
310  errmsg("could not set the cipher list (no valid ciphers available)")));
311  goto error;
312  }
313 
314  /* Let server choose order */
316  SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
317 
318  /*
319  * Load CA store, so we can verify client certificates if needed.
320  */
321  if (ssl_ca_file[0])
322  {
323  if (SSL_CTX_load_verify_locations(context, ssl_ca_file, NULL) != 1 ||
324  (root_cert_list = SSL_load_client_CA_file(ssl_ca_file)) == NULL)
325  {
326  ereport(isServerStart ? FATAL : LOG,
327  (errcode(ERRCODE_CONFIG_FILE_ERROR),
328  errmsg("could not load root certificate file \"%s\": %s",
329  ssl_ca_file, SSLerrmessage(ERR_get_error()))));
330  goto error;
331  }
332  }
333 
334  /*----------
335  * Load the Certificate Revocation List (CRL).
336  * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
337  *----------
338  */
339  if (ssl_crl_file[0])
340  {
341  X509_STORE *cvstore = SSL_CTX_get_cert_store(context);
342 
343  if (cvstore)
344  {
345  /* Set the flags to check against the complete CRL chain */
346  if (X509_STORE_load_locations(cvstore, ssl_crl_file, NULL) == 1)
347  {
348  /* OpenSSL 0.96 does not support X509_V_FLAG_CRL_CHECK */
349 #ifdef X509_V_FLAG_CRL_CHECK
350  X509_STORE_set_flags(cvstore,
351  X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
352 #else
353  ereport(LOG,
354  (errcode(ERRCODE_CONFIG_FILE_ERROR),
355  errmsg("SSL certificate revocation list file \"%s\" ignored",
356  ssl_crl_file),
357  errdetail("SSL library does not support certificate revocation lists.")));
358 #endif
359  }
360  else
361  {
362  ereport(isServerStart ? FATAL : LOG,
363  (errcode(ERRCODE_CONFIG_FILE_ERROR),
364  errmsg("could not load SSL certificate revocation list file \"%s\": %s",
365  ssl_crl_file, SSLerrmessage(ERR_get_error()))));
366  goto error;
367  }
368  }
369  }
370 
371  if (ssl_ca_file[0])
372  {
373  /*
374  * Always ask for SSL client cert, but don't fail if it's not
375  * presented. We might fail such connections later, depending on what
376  * we find in pg_hba.conf.
377  */
378  SSL_CTX_set_verify(context,
379  (SSL_VERIFY_PEER |
380  SSL_VERIFY_CLIENT_ONCE),
381  verify_cb);
382 
383  /*
384  * Tell OpenSSL to send the list of root certs we trust to clients in
385  * CertificateRequests. This lets a client with a keystore select the
386  * appropriate client certificate to send to us.
387  */
388  SSL_CTX_set_client_CA_list(context, root_cert_list);
389  }
390 
391  /*
392  * Success! Replace any existing SSL_context.
393  */
394  if (SSL_context)
395  SSL_CTX_free(SSL_context);
396 
397  SSL_context = context;
398 
399  /*
400  * Set flag to remember whether CA store has been loaded into SSL_context.
401  */
402  if (ssl_ca_file[0])
404  else
406 
407  return 0;
408 
409 error:
410  if (context)
411  SSL_CTX_free(context);
412  return -1;
413 }
414 
415 /*
416  * Destroy global SSL context, if any.
417  */
418 void
420 {
421  if (SSL_context)
422  SSL_CTX_free(SSL_context);
423  SSL_context = NULL;
425 }
426 
427 /*
428  * Attempt to negotiate SSL connection.
429  */
430 int
432 {
433  int r;
434  int err;
435  int waitfor;
436  unsigned long ecode;
437 
438  Assert(!port->ssl);
439  Assert(!port->peer);
440 
441  if (!SSL_context)
442  {
444  (errcode(ERRCODE_PROTOCOL_VIOLATION),
445  errmsg("could not initialize SSL connection: SSL context not set up")));
446  return -1;
447  }
448 
449  if (!(port->ssl = SSL_new(SSL_context)))
450  {
452  (errcode(ERRCODE_PROTOCOL_VIOLATION),
453  errmsg("could not initialize SSL connection: %s",
454  SSLerrmessage(ERR_get_error()))));
455  return -1;
456  }
457  if (!my_SSL_set_fd(port, port->sock))
458  {
460  (errcode(ERRCODE_PROTOCOL_VIOLATION),
461  errmsg("could not set SSL socket: %s",
462  SSLerrmessage(ERR_get_error()))));
463  return -1;
464  }
465  port->ssl_in_use = true;
466 
467 aloop:
468 
469  /*
470  * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
471  * queue. In general, the current thread's error queue must be empty
472  * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
473  * not work reliably. An extension may have failed to clear the
474  * per-thread error queue following another call to an OpenSSL I/O
475  * routine.
476  */
477  ERR_clear_error();
478  r = SSL_accept(port->ssl);
479  if (r <= 0)
480  {
481  err = SSL_get_error(port->ssl, r);
482 
483  /*
484  * Other clients of OpenSSL in the backend may fail to call
485  * ERR_get_error(), but we always do, so as to not cause problems for
486  * OpenSSL clients that don't call ERR_clear_error() defensively. Be
487  * sure that this happens by calling now. SSL_get_error() relies on
488  * the OpenSSL per-thread error queue being intact, so this is the
489  * earliest possible point ERR_get_error() may be called.
490  */
491  ecode = ERR_get_error();
492  switch (err)
493  {
494  case SSL_ERROR_WANT_READ:
495  case SSL_ERROR_WANT_WRITE:
496  /* not allowed during connection establishment */
497  Assert(!port->noblock);
498 
499  /*
500  * No need to care about timeouts/interrupts here. At this
501  * point authentication_timeout still employs
502  * StartupPacketTimeoutHandler() which directly exits.
503  */
504  if (err == SSL_ERROR_WANT_READ)
505  waitfor = WL_SOCKET_READABLE;
506  else
507  waitfor = WL_SOCKET_WRITEABLE;
508 
509  WaitLatchOrSocket(MyLatch, waitfor, port->sock, 0,
511  goto aloop;
512  case SSL_ERROR_SYSCALL:
513  if (r < 0)
516  errmsg("could not accept SSL connection: %m")));
517  else
519  (errcode(ERRCODE_PROTOCOL_VIOLATION),
520  errmsg("could not accept SSL connection: EOF detected")));
521  break;
522  case SSL_ERROR_SSL:
524  (errcode(ERRCODE_PROTOCOL_VIOLATION),
525  errmsg("could not accept SSL connection: %s",
526  SSLerrmessage(ecode))));
527  break;
528  case SSL_ERROR_ZERO_RETURN:
530  (errcode(ERRCODE_PROTOCOL_VIOLATION),
531  errmsg("could not accept SSL connection: EOF detected")));
532  break;
533  default:
535  (errcode(ERRCODE_PROTOCOL_VIOLATION),
536  errmsg("unrecognized SSL error code: %d",
537  err)));
538  break;
539  }
540  return -1;
541  }
542 
543  /* Get client certificate, if available. */
544  port->peer = SSL_get_peer_certificate(port->ssl);
545 
546  /* and extract the Common Name from it. */
547  port->peer_cn = NULL;
548  port->peer_cert_valid = false;
549  if (port->peer != NULL)
550  {
551  int len;
552 
553  len = X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer),
554  NID_commonName, NULL, 0);
555  if (len != -1)
556  {
557  char *peer_cn;
558 
559  peer_cn = MemoryContextAlloc(TopMemoryContext, len + 1);
560  r = X509_NAME_get_text_by_NID(X509_get_subject_name(port->peer),
561  NID_commonName, peer_cn, len + 1);
562  peer_cn[len] = '\0';
563  if (r != len)
564  {
565  /* shouldn't happen */
566  pfree(peer_cn);
567  return -1;
568  }
569 
570  /*
571  * Reject embedded NULLs in certificate common name to prevent
572  * attacks like CVE-2009-4034.
573  */
574  if (len != strlen(peer_cn))
575  {
577  (errcode(ERRCODE_PROTOCOL_VIOLATION),
578  errmsg("SSL certificate's common name contains embedded null")));
579  pfree(peer_cn);
580  return -1;
581  }
582 
583  port->peer_cn = peer_cn;
584  }
585  port->peer_cert_valid = true;
586  }
587 
588  ereport(DEBUG2,
589  (errmsg("SSL connection from \"%s\"",
590  port->peer_cn ? port->peer_cn : "(anonymous)")));
591 
592  /* set up debugging/info callback */
593  SSL_CTX_set_info_callback(SSL_context, info_cb);
594 
595  return 0;
596 }
597 
598 /*
599  * Close SSL connection.
600  */
601 void
603 {
604  if (port->ssl)
605  {
606  SSL_shutdown(port->ssl);
607  SSL_free(port->ssl);
608  port->ssl = NULL;
609  port->ssl_in_use = false;
610  }
611 
612  if (port->peer)
613  {
614  X509_free(port->peer);
615  port->peer = NULL;
616  }
617 
618  if (port->peer_cn)
619  {
620  pfree(port->peer_cn);
621  port->peer_cn = NULL;
622  }
623 }
624 
625 /*
626  * Read data from a secure connection.
627  */
628 ssize_t
629 be_tls_read(Port *port, void *ptr, size_t len, int *waitfor)
630 {
631  ssize_t n;
632  int err;
633  unsigned long ecode;
634 
635  errno = 0;
636  ERR_clear_error();
637  n = SSL_read(port->ssl, ptr, len);
638  err = SSL_get_error(port->ssl, n);
639  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
640  switch (err)
641  {
642  case SSL_ERROR_NONE:
643  /* a-ok */
644  break;
645  case SSL_ERROR_WANT_READ:
646  *waitfor = WL_SOCKET_READABLE;
647  errno = EWOULDBLOCK;
648  n = -1;
649  break;
650  case SSL_ERROR_WANT_WRITE:
651  *waitfor = WL_SOCKET_WRITEABLE;
652  errno = EWOULDBLOCK;
653  n = -1;
654  break;
655  case SSL_ERROR_SYSCALL:
656  /* leave it to caller to ereport the value of errno */
657  if (n != -1)
658  {
659  errno = ECONNRESET;
660  n = -1;
661  }
662  break;
663  case SSL_ERROR_SSL:
665  (errcode(ERRCODE_PROTOCOL_VIOLATION),
666  errmsg("SSL error: %s", SSLerrmessage(ecode))));
667  errno = ECONNRESET;
668  n = -1;
669  break;
670  case SSL_ERROR_ZERO_RETURN:
671  /* connection was cleanly shut down by peer */
672  n = 0;
673  break;
674  default:
676  (errcode(ERRCODE_PROTOCOL_VIOLATION),
677  errmsg("unrecognized SSL error code: %d",
678  err)));
679  errno = ECONNRESET;
680  n = -1;
681  break;
682  }
683 
684  return n;
685 }
686 
687 /*
688  * Write data to a secure connection.
689  */
690 ssize_t
691 be_tls_write(Port *port, void *ptr, size_t len, int *waitfor)
692 {
693  ssize_t n;
694  int err;
695  unsigned long ecode;
696 
697  errno = 0;
698  ERR_clear_error();
699  n = SSL_write(port->ssl, ptr, len);
700  err = SSL_get_error(port->ssl, n);
701  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
702  switch (err)
703  {
704  case SSL_ERROR_NONE:
705  /* a-ok */
706  break;
707  case SSL_ERROR_WANT_READ:
708  *waitfor = WL_SOCKET_READABLE;
709  errno = EWOULDBLOCK;
710  n = -1;
711  break;
712  case SSL_ERROR_WANT_WRITE:
713  *waitfor = WL_SOCKET_WRITEABLE;
714  errno = EWOULDBLOCK;
715  n = -1;
716  break;
717  case SSL_ERROR_SYSCALL:
718  /* leave it to caller to ereport the value of errno */
719  if (n != -1)
720  {
721  errno = ECONNRESET;
722  n = -1;
723  }
724  break;
725  case SSL_ERROR_SSL:
727  (errcode(ERRCODE_PROTOCOL_VIOLATION),
728  errmsg("SSL error: %s", SSLerrmessage(ecode))));
729  errno = ECONNRESET;
730  n = -1;
731  break;
732  case SSL_ERROR_ZERO_RETURN:
733 
734  /*
735  * the SSL connnection was closed, leave it to the caller to
736  * ereport it
737  */
738  errno = ECONNRESET;
739  n = -1;
740  break;
741  default:
743  (errcode(ERRCODE_PROTOCOL_VIOLATION),
744  errmsg("unrecognized SSL error code: %d",
745  err)));
746  errno = ECONNRESET;
747  n = -1;
748  break;
749  }
750 
751  return n;
752 }
753 
754 /* ------------------------------------------------------------ */
755 /* Internal functions */
756 /* ------------------------------------------------------------ */
757 
758 /*
759  * Private substitute BIO: this does the sending and receiving using send() and
760  * recv() instead. This is so that we can enable and disable interrupts
761  * just while calling recv(). We cannot have interrupts occurring while
762  * the bulk of openssl runs, because it uses malloc() and possibly other
763  * non-reentrant libc facilities. We also need to call send() and recv()
764  * directly so it gets passed through the socket/signals layer on Win32.
765  *
766  * These functions are closely modelled on the standard socket BIO in OpenSSL;
767  * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
768  * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
769  * to retry; do we need to adopt their logic for that?
770  */
771 
772 #ifndef HAVE_BIO_GET_DATA
773 #define BIO_get_data(bio) (bio->ptr)
774 #define BIO_set_data(bio, data) (bio->ptr = data)
775 #endif
776 
777 static BIO_METHOD *my_bio_methods = NULL;
778 
779 static int
780 my_sock_read(BIO *h, char *buf, int size)
781 {
782  int res = 0;
783 
784  if (buf != NULL)
785  {
786  res = secure_raw_read(((Port *) BIO_get_data(h)), buf, size);
787  BIO_clear_retry_flags(h);
788  if (res <= 0)
789  {
790  /* If we were interrupted, tell caller to retry */
791  if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
792  {
793  BIO_set_retry_read(h);
794  }
795  }
796  }
797 
798  return res;
799 }
800 
801 static int
802 my_sock_write(BIO *h, const char *buf, int size)
803 {
804  int res = 0;
805 
806  res = secure_raw_write(((Port *) BIO_get_data(h)), buf, size);
807  BIO_clear_retry_flags(h);
808  if (res <= 0)
809  {
810  /* If we were interrupted, tell caller to retry */
811  if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
812  {
813  BIO_set_retry_write(h);
814  }
815  }
816 
817  return res;
818 }
819 
820 static BIO_METHOD *
822 {
823  if (!my_bio_methods)
824  {
825  BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
826 #ifdef HAVE_BIO_METH_NEW
827  int my_bio_index;
828 
829  my_bio_index = BIO_get_new_index();
830  if (my_bio_index == -1)
831  return NULL;
832  my_bio_methods = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
833  if (!my_bio_methods)
834  return NULL;
835  if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
836  !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
837  !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
838  !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
839  !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
840  !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
841  !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
842  !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
843  {
844  BIO_meth_free(my_bio_methods);
845  my_bio_methods = NULL;
846  return NULL;
847  }
848 #else
849  my_bio_methods = malloc(sizeof(BIO_METHOD));
850  if (!my_bio_methods)
851  return NULL;
852  memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
853  my_bio_methods->bread = my_sock_read;
854  my_bio_methods->bwrite = my_sock_write;
855 #endif
856  }
857  return my_bio_methods;
858 }
859 
860 /* This should exactly match openssl's SSL_set_fd except for using my BIO */
861 static int
863 {
864  int ret = 0;
865  BIO *bio;
866  BIO_METHOD *bio_method;
867 
868  bio_method = my_BIO_s_socket();
869  if (bio_method == NULL)
870  {
871  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
872  goto err;
873  }
874  bio = BIO_new(bio_method);
875 
876  if (bio == NULL)
877  {
878  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
879  goto err;
880  }
881  BIO_set_data(bio, port);
882 
883  BIO_set_fd(bio, fd, BIO_NOCLOSE);
884  SSL_set_bio(port->ssl, bio, bio);
885  ret = 1;
886 err:
887  return ret;
888 }
889 
890 /*
891  * Load precomputed DH parameters.
892  *
893  * To prevent "downgrade" attacks, we perform a number of checks
894  * to verify that the DBA-generated DH parameters file contains
895  * what we expect it to contain.
896  */
897 static DH *
898 load_dh_file(char *filename, bool isServerStart)
899 {
900  FILE *fp;
901  DH *dh = NULL;
902  int codes;
903 
904  /* attempt to open file. It's not an error if it doesn't exist. */
905  if ((fp = AllocateFile(filename, "r")) == NULL)
906  {
907  ereport(isServerStart ? FATAL : LOG,
909  errmsg("could not open DH parameters file \"%s\": %m",
910  filename)));
911  return NULL;
912  }
913 
914  dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
915  FreeFile(fp);
916 
917  if (dh == NULL)
918  {
919  ereport(isServerStart ? FATAL : LOG,
920  (errcode(ERRCODE_CONFIG_FILE_ERROR),
921  errmsg("could not load DH parameters file: %s",
922  SSLerrmessage(ERR_get_error()))));
923  return NULL;
924  }
925 
926  /* make sure the DH parameters are usable */
927  if (DH_check(dh, &codes) == 0)
928  {
929  ereport(isServerStart ? FATAL : LOG,
930  (errcode(ERRCODE_CONFIG_FILE_ERROR),
931  errmsg("invalid DH parameters: %s",
932  SSLerrmessage(ERR_get_error()))));
933  return NULL;
934  }
935  if (codes & DH_CHECK_P_NOT_PRIME)
936  {
937  ereport(isServerStart ? FATAL : LOG,
938  (errcode(ERRCODE_CONFIG_FILE_ERROR),
939  errmsg("invalid DH parameters: p is not prime")));
940  return NULL;
941  }
942  if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
943  (codes & DH_CHECK_P_NOT_SAFE_PRIME))
944  {
945  ereport(isServerStart ? FATAL : LOG,
946  (errcode(ERRCODE_CONFIG_FILE_ERROR),
947  errmsg("invalid DH parameters: neither suitable generator or safe prime")));
948  return NULL;
949  }
950 
951  return dh;
952 }
953 
954 /*
955  * Load hardcoded DH parameters.
956  *
957  * To prevent problems if the DH parameters files don't even
958  * exist, we can load DH parameters hardcoded into this file.
959  */
960 static DH *
961 load_dh_buffer(const char *buffer, size_t len)
962 {
963  BIO *bio;
964  DH *dh = NULL;
965 
966  bio = BIO_new_mem_buf((char *) buffer, len);
967  if (bio == NULL)
968  return NULL;
969  dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
970  if (dh == NULL)
971  ereport(DEBUG2,
972  (errmsg_internal("DH load buffer: %s",
973  SSLerrmessage(ERR_get_error()))));
974  BIO_free(bio);
975 
976  return dh;
977 }
978 
979 /*
980  * Passphrase collection callback
981  *
982  * If OpenSSL is told to use a passphrase-protected server key, by default
983  * it will issue a prompt on /dev/tty and try to read a key from there.
984  * That's no good during a postmaster SIGHUP cycle, not to mention SSL context
985  * reload in an EXEC_BACKEND postmaster child. So override it with this dummy
986  * function that just returns an empty passphrase, guaranteeing failure.
987  */
988 static int
989 ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
990 {
991  /* Set flag to change the error message we'll report */
992  ssl_passwd_cb_called = true;
993  /* And return empty string */
994  Assert(size > 0);
995  buf[0] = '\0';
996  return 0;
997 }
998 
999 /*
1000  * Certificate verification callback
1001  *
1002  * This callback allows us to log intermediate problems during
1003  * verification, but for now we'll see if the final error message
1004  * contains enough information.
1005  *
1006  * This callback also allows us to override the default acceptance
1007  * criteria (e.g., accepting self-signed or expired certs), but
1008  * for now we accept the default checks.
1009  */
1010 static int
1011 verify_cb(int ok, X509_STORE_CTX *ctx)
1012 {
1013  return ok;
1014 }
1015 
1016 /*
1017  * This callback is used to copy SSL information messages
1018  * into the PostgreSQL log.
1019  */
1020 static void
1021 info_cb(const SSL *ssl, int type, int args)
1022 {
1023  switch (type)
1024  {
1025  case SSL_CB_HANDSHAKE_START:
1026  ereport(DEBUG4,
1027  (errmsg_internal("SSL: handshake start")));
1028  break;
1029  case SSL_CB_HANDSHAKE_DONE:
1030  ereport(DEBUG4,
1031  (errmsg_internal("SSL: handshake done")));
1032  break;
1033  case SSL_CB_ACCEPT_LOOP:
1034  ereport(DEBUG4,
1035  (errmsg_internal("SSL: accept loop")));
1036  break;
1037  case SSL_CB_ACCEPT_EXIT:
1038  ereport(DEBUG4,
1039  (errmsg_internal("SSL: accept exit (%d)", args)));
1040  break;
1041  case SSL_CB_CONNECT_LOOP:
1042  ereport(DEBUG4,
1043  (errmsg_internal("SSL: connect loop")));
1044  break;
1045  case SSL_CB_CONNECT_EXIT:
1046  ereport(DEBUG4,
1047  (errmsg_internal("SSL: connect exit (%d)", args)));
1048  break;
1049  case SSL_CB_READ_ALERT:
1050  ereport(DEBUG4,
1051  (errmsg_internal("SSL: read alert (0x%04x)", args)));
1052  break;
1053  case SSL_CB_WRITE_ALERT:
1054  ereport(DEBUG4,
1055  (errmsg_internal("SSL: write alert (0x%04x)", args)));
1056  break;
1057  }
1058 }
1059 
1060 /*
1061  * Set DH parameters for generating ephemeral DH keys. The
1062  * DH parameters can take a long time to compute, so they must be
1063  * precomputed.
1064  *
1065  * Since few sites will bother to create a parameter file, we also
1066  * also provide a fallback to the parameters provided by the
1067  * OpenSSL project.
1068  *
1069  * These values can be static (once loaded or computed) since the
1070  * OpenSSL library can efficiently generate random keys from the
1071  * information provided.
1072  */
1073 static bool
1074 initialize_dh(SSL_CTX *context, bool isServerStart)
1075 {
1076  DH *dh = NULL;
1077 
1078  SSL_CTX_set_options(context, SSL_OP_SINGLE_DH_USE);
1079 
1080  if (ssl_dh_params_file[0])
1081  dh = load_dh_file(ssl_dh_params_file, isServerStart);
1082  if (!dh)
1083  dh = load_dh_buffer(file_dh2048, sizeof file_dh2048);
1084  if (!dh)
1085  {
1086  ereport(isServerStart ? FATAL : LOG,
1087  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1088  (errmsg("DH: could not load DH parameters"))));
1089  return false;
1090  }
1091 
1092  if (SSL_CTX_set_tmp_dh(context, dh) != 1)
1093  {
1094  ereport(isServerStart ? FATAL : LOG,
1095  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1096  (errmsg("DH: could not set DH parameters: %s",
1097  SSLerrmessage(ERR_get_error())))));
1098  return false;
1099  }
1100  return true;
1101 }
1102 
1103 /*
1104  * Set ECDH parameters for generating ephemeral Elliptic Curve DH
1105  * keys. This is much simpler than the DH parameters, as we just
1106  * need to provide the name of the curve to OpenSSL.
1107  */
1108 static bool
1109 initialize_ecdh(SSL_CTX *context, bool isServerStart)
1110 {
1111 #ifndef OPENSSL_NO_ECDH
1112  EC_KEY *ecdh;
1113  int nid;
1114 
1115  nid = OBJ_sn2nid(SSLECDHCurve);
1116  if (!nid)
1117  {
1118  ereport(isServerStart ? FATAL : LOG,
1119  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1120  errmsg("ECDH: unrecognized curve name: %s", SSLECDHCurve)));
1121  return false;
1122  }
1123 
1124  ecdh = EC_KEY_new_by_curve_name(nid);
1125  if (!ecdh)
1126  {
1127  ereport(isServerStart ? FATAL : LOG,
1128  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1129  errmsg("ECDH: could not create key")));
1130  return false;
1131  }
1132 
1133  SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
1134  SSL_CTX_set_tmp_ecdh(context, ecdh);
1135  EC_KEY_free(ecdh);
1136 #endif
1137 
1138  return true;
1139 }
1140 
1141 /*
1142  * Obtain reason string for passed SSL errcode
1143  *
1144  * ERR_get_error() is used by caller to get errcode to pass here.
1145  *
1146  * Some caution is needed here since ERR_reason_error_string will
1147  * return NULL if it doesn't recognize the error code. We don't
1148  * want to return NULL ever.
1149  */
1150 static const char *
1151 SSLerrmessage(unsigned long ecode)
1152 {
1153  const char *errreason;
1154  static char errbuf[32];
1155 
1156  if (ecode == 0)
1157  return _("no SSL error reported");
1158  errreason = ERR_reason_error_string(ecode);
1159  if (errreason != NULL)
1160  return errreason;
1161  snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), ecode);
1162  return errbuf;
1163 }
1164 
1165 /*
1166  * Return information about the SSL connection
1167  */
1168 int
1170 {
1171  int bits;
1172 
1173  if (port->ssl)
1174  {
1175  SSL_get_cipher_bits(port->ssl, &bits);
1176  return bits;
1177  }
1178  else
1179  return 0;
1180 }
1181 
1182 bool
1184 {
1185  if (port->ssl)
1186  return (SSL_get_current_compression(port->ssl) != NULL);
1187  else
1188  return false;
1189 }
1190 
1191 void
1192 be_tls_get_version(Port *port, char *ptr, size_t len)
1193 {
1194  if (port->ssl)
1195  strlcpy(ptr, SSL_get_version(port->ssl), len);
1196  else
1197  ptr[0] = '\0';
1198 }
1199 
1200 void
1201 be_tls_get_cipher(Port *port, char *ptr, size_t len)
1202 {
1203  if (port->ssl)
1204  strlcpy(ptr, SSL_get_cipher(port->ssl), len);
1205  else
1206  ptr[0] = '\0';
1207 }
1208 
1209 void
1210 be_tls_get_peerdn_name(Port *port, char *ptr, size_t len)
1211 {
1212  if (port->peer)
1213  strlcpy(ptr, X509_NAME_to_cstring(X509_get_subject_name(port->peer)), len);
1214  else
1215  ptr[0] = '\0';
1216 }
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 }
#define EWOULDBLOCK
Definition: win32.h:291
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 BIO_METHOD * my_BIO_s_socket(void)
static DH * load_dh_file(char *filename, bool isServerStart)
char * peer_cn
Definition: libpq-be.h:182
#define BIO_get_data(bio)
char * pstrdup(const char *in)
Definition: mcxt.c:1076
bool ssl_loaded_verify_locations
bool peer_cert_valid
Definition: libpq-be.h:183
ssize_t secure_raw_write(Port *port, const void *ptr, size_t len)
Definition: be-secure.c:303
static void info_cb(const SSL *ssl, int type, int args)
int errcode(int sqlerrcode)
Definition: elog.c:575
Definition: libpq-be.h:116
return result
Definition: formatting.c:1633
bool ssl_in_use
Definition: libpq-be.h:181
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define WL_SOCKET_READABLE
Definition: latch.h:125
char * ssl_cert_file
Definition: be-secure.c:43
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:46
static int fd(const char *x, int i)
Definition: preproc-init.c:105
pgsocket sock
Definition: libpq-be.h:118
int be_tls_init(bool isServerStart)
#define ECONNRESET
Definition: win32.h:295
#define S_IXGRP
Definition: win32.h:450
#define malloc(a)
Definition: header.h:50
#define EAGAIN
Definition: win32.h:283
void pfree(void *pointer)
Definition: mcxt.c:949
static int my_SSL_set_fd(Port *port, int fd)
#define S_IWGRP
Definition: win32.h:449
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
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define COMMERROR
Definition: elog.h:30
int errcode_for_file_access(void)
Definition: elog.c:598
static bool SSL_initialized
char * SSLCipherSuites
Definition: be-secure.c:54
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2094
static int verify_cb(int, X509_STORE_CTX *)
static DH * load_dh_buffer(const char *, size_t)
static int ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
void be_tls_destroy(void)
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
static char * X509_NAME_to_cstring(X509_NAME *name)
int errcode_for_socket_access(void)
Definition: elog.c:669
static int port
Definition: pg_regress.c:89
static const char file_dh2048[]
#define SSL_get_current_compression(x)
Definition: port.h:422
int be_tls_get_cipher_bits(Port *port)
#define EINTR
Definition: win32.h:285
static bool initialize_dh(SSL_CTX *context, bool isServerStart)
void be_tls_get_version(Port *port, char *ptr, size_t len)
char * ssl_ca_file
Definition: be-secure.c:45
#define S_IRWXO
Definition: win32.h:455
int be_tls_open_server(Port *port)
void be_tls_get_peerdn_name(Port *port, char *ptr, size_t len)
ssize_t secure_raw_read(Port *port, void *ptr, size_t len)
Definition: be-secure.c:217
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
int errmsg_internal(const char *fmt,...)
Definition: elog.c:827
static BIO_METHOD * my_bio_methods
#define Assert(condition)
Definition: c.h:664
int WaitLatchOrSocket(volatile Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:356
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:214
static int my_sock_read(BIO *h, char *buf, int size)
bool noblock
Definition: libpq-be.h:119
char * ssl_dh_params_file
Definition: be-secure.c:47
const char * name
Definition: encode.c:521
static bool ssl_passwd_cb_called
#define S_IRWXG
Definition: win32.h:451
int FreeFile(FILE *file)
Definition: fd.c:2277
static char * filename
Definition: pg_dumpall.c:90
e
Definition: preproc-init.c:82
int errmsg(const char *fmt,...)
Definition: elog.c:797
static SSL_CTX * SSL_context
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:706
void be_tls_get_cipher(Port *port, char *ptr, size_t len)
static int my_sock_write(BIO *h, const char *buf, int size)
int i
static const char * SSLerrmessage(unsigned long ecode)
void be_tls_close(Port *port)
struct Latch * MyLatch
Definition: globals.c:52
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:572
#define _(x)
Definition: elog.c:84
char * ssl_key_file
Definition: be-secure.c:44
bool SSLPreferServerCiphers
Definition: be-secure.c:60