PostgreSQL Source Code  git master
be-secure-openssl.c File Reference
#include "postgres.h"
#include <sys/stat.h>
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include "common/string.h"
#include "libpq/libpq.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "storage/fd.h"
#include "storage/latch.h"
#include "tcop/tcopprot.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "common/openssl.h"
#include <openssl/conf.h>
#include <openssl/dh.h>
#include <openssl/ec.h>
#include <openssl/x509v3.h>
Include dependency graph for be-secure-openssl.c:

Go to the source code of this file.

Macros

#define BIO_get_data(bio)   (bio->ptr)
 
#define BIO_set_data(bio, data)   (bio->ptr = data)
 
#define MAXLEN   71
 

Functions

static void default_openssl_tls_init (SSL_CTX *context, bool isServerStart)
 
static int my_sock_read (BIO *h, char *buf, int size)
 
static int my_sock_write (BIO *h, const char *buf, int size)
 
static BIO_METHOD * my_BIO_s_socket (void)
 
static int my_SSL_set_fd (Port *port, int fd)
 
static DH * load_dh_file (char *filename, bool isServerStart)
 
static DH * load_dh_buffer (const char *buffer, size_t len)
 
static int ssl_external_passwd_cb (char *buf, int size, int rwflag, void *userdata)
 
static int dummy_ssl_passwd_cb (char *buf, int size, int rwflag, void *userdata)
 
static int verify_cb (int ok, X509_STORE_CTX *ctx)
 
static void info_cb (const SSL *ssl, int type, int args)
 
static bool initialize_dh (SSL_CTX *context, bool isServerStart)
 
static bool initialize_ecdh (SSL_CTX *context, bool isServerStart)
 
static const char * SSLerrmessage (unsigned long ecode)
 
static char * X509_NAME_to_cstring (X509_NAME *name)
 
static int ssl_protocol_version_to_openssl (int v)
 
static const char * ssl_protocol_version_to_string (int v)
 
int be_tls_init (bool isServerStart)
 
void be_tls_destroy (void)
 
int be_tls_open_server (Port *port)
 
void be_tls_close (Port *port)
 
ssize_t be_tls_read (Port *port, void *ptr, size_t len, int *waitfor)
 
ssize_t be_tls_write (Port *port, void *ptr, size_t len, int *waitfor)
 
static char * prepare_cert_name (char *name)
 
int be_tls_get_cipher_bits (Port *port)
 
const char * be_tls_get_version (Port *port)
 
const char * be_tls_get_cipher (Port *port)
 
void be_tls_get_peer_subject_name (Port *port, char *ptr, size_t len)
 
void be_tls_get_peer_issuer_name (Port *port, char *ptr, size_t len)
 
void be_tls_get_peer_serial (Port *port, char *ptr, size_t len)
 

Variables

openssl_tls_init_hook_typ openssl_tls_init_hook = default_openssl_tls_init
 
static SSL_CTX * SSL_context = NULL
 
static bool SSL_initialized = false
 
static bool dummy_ssl_passwd_cb_called = false
 
static bool ssl_is_server_start
 
static const char * cert_errdetail
 
static BIO_METHOD * my_bio_methods = NULL
 

Macro Definition Documentation

◆ BIO_get_data

#define BIO_get_data (   bio)    (bio->ptr)

Definition at line 839 of file be-secure-openssl.c.

◆ BIO_set_data

#define BIO_set_data (   bio,
  data 
)    (bio->ptr = data)

Definition at line 840 of file be-secure-openssl.c.

◆ MAXLEN

#define MAXLEN   71

Function Documentation

◆ be_tls_close()

void be_tls_close ( Port port)

Definition at line 668 of file be-secure-openssl.c.

669 {
670  if (port->ssl)
671  {
672  SSL_shutdown(port->ssl);
673  SSL_free(port->ssl);
674  port->ssl = NULL;
675  port->ssl_in_use = false;
676  }
677 
678  if (port->peer)
679  {
680  X509_free(port->peer);
681  port->peer = NULL;
682  }
683 
684  if (port->peer_cn)
685  {
686  pfree(port->peer_cn);
687  port->peer_cn = NULL;
688  }
689 
690  if (port->peer_dn)
691  {
692  pfree(port->peer_dn);
693  port->peer_dn = NULL;
694  }
695 }
void pfree(void *pointer)
Definition: mcxt.c:1306
static int port
Definition: pg_regress.c:90

References pfree(), and port.

Referenced by secure_close().

◆ be_tls_destroy()

void be_tls_destroy ( void  )

Definition at line 404 of file be-secure-openssl.c.

405 {
406  if (SSL_context)
407  SSL_CTX_free(SSL_context);
408  SSL_context = NULL;
409  ssl_loaded_verify_locations = false;
410 }
static SSL_CTX * SSL_context

References SSL_context.

Referenced by secure_destroy().

◆ be_tls_get_cipher()

const char* be_tls_get_cipher ( Port port)

Definition at line 1385 of file be-secure-openssl.c.

1386 {
1387  if (port->ssl)
1388  return SSL_get_cipher(port->ssl);
1389  else
1390  return NULL;
1391 }

References port.

Referenced by PerformAuthentication(), pgstat_bestart(), and ssl_cipher().

◆ be_tls_get_cipher_bits()

int be_tls_get_cipher_bits ( Port port)

Definition at line 1362 of file be-secure-openssl.c.

1363 {
1364  int bits;
1365 
1366  if (port->ssl)
1367  {
1368  SSL_get_cipher_bits(port->ssl, &bits);
1369  return bits;
1370  }
1371  else
1372  return 0;
1373 }

References port.

Referenced by PerformAuthentication(), and pgstat_bestart().

◆ be_tls_get_peer_issuer_name()

void be_tls_get_peer_issuer_name ( Port port,
char *  ptr,
size_t  len 
)

Definition at line 1403 of file be-secure-openssl.c.

1404 {
1405  if (port->peer)
1406  strlcpy(ptr, X509_NAME_to_cstring(X509_get_issuer_name(port->peer)), len);
1407  else
1408  ptr[0] = '\0';
1409 }
static char * X509_NAME_to_cstring(X509_NAME *name)
const void size_t len
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45

References len, port, strlcpy(), and X509_NAME_to_cstring().

Referenced by pgstat_bestart(), and ssl_issuer_dn().

◆ be_tls_get_peer_serial()

void be_tls_get_peer_serial ( Port port,
char *  ptr,
size_t  len 
)

Definition at line 1412 of file be-secure-openssl.c.

1413 {
1414  if (port->peer)
1415  {
1416  ASN1_INTEGER *serial;
1417  BIGNUM *b;
1418  char *decimal;
1419 
1420  serial = X509_get_serialNumber(port->peer);
1421  b = ASN1_INTEGER_to_BN(serial, NULL);
1422  decimal = BN_bn2dec(b);
1423 
1424  BN_free(b);
1425  strlcpy(ptr, decimal, len);
1426  OPENSSL_free(decimal);
1427  }
1428  else
1429  ptr[0] = '\0';
1430 }
int b
Definition: isn.c:70

References b, len, port, and strlcpy().

Referenced by pgstat_bestart(), and ssl_client_serial().

◆ be_tls_get_peer_subject_name()

void be_tls_get_peer_subject_name ( Port port,
char *  ptr,
size_t  len 
)

Definition at line 1394 of file be-secure-openssl.c.

1395 {
1396  if (port->peer)
1397  strlcpy(ptr, X509_NAME_to_cstring(X509_get_subject_name(port->peer)), len);
1398  else
1399  ptr[0] = '\0';
1400 }

References len, port, strlcpy(), and X509_NAME_to_cstring().

Referenced by pgstat_bestart(), and ssl_client_dn().

◆ be_tls_get_version()

const char* be_tls_get_version ( Port port)

Definition at line 1376 of file be-secure-openssl.c.

1377 {
1378  if (port->ssl)
1379  return SSL_get_version(port->ssl);
1380  else
1381  return NULL;
1382 }

References port.

Referenced by PerformAuthentication(), pgstat_bestart(), and ssl_version().

◆ be_tls_init()

int be_tls_init ( bool  isServerStart)

Definition at line 92 of file be-secure-openssl.c.

93 {
94  SSL_CTX *context;
95  int ssl_ver_min = -1;
96  int ssl_ver_max = -1;
97 
98  /* This stuff need be done only once. */
99  if (!SSL_initialized)
100  {
101 #ifdef HAVE_OPENSSL_INIT_SSL
102  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
103 #else
104  OPENSSL_config(NULL);
105  SSL_library_init();
106  SSL_load_error_strings();
107 #endif
108  SSL_initialized = true;
109  }
110 
111  /*
112  * Create a new SSL context into which we'll load all the configuration
113  * settings. If we fail partway through, we can avoid memory leakage by
114  * freeing this context; we don't install it as active until the end.
115  *
116  * We use SSLv23_method() because it can negotiate use of the highest
117  * mutually supported protocol version, while alternatives like
118  * TLSv1_2_method() permit only one specific version. Note that we don't
119  * actually allow SSL v2 or v3, only TLS protocols (see below).
120  */
121  context = SSL_CTX_new(SSLv23_method());
122  if (!context)
123  {
124  ereport(isServerStart ? FATAL : LOG,
125  (errmsg("could not create SSL context: %s",
126  SSLerrmessage(ERR_get_error()))));
127  goto error;
128  }
129 
130  /*
131  * Disable OpenSSL's moving-write-buffer sanity check, because it causes
132  * unnecessary failures in nonblocking send cases.
133  */
134  SSL_CTX_set_mode(context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
135 
136  /*
137  * Call init hook (usually to set password callback)
138  */
139  (*openssl_tls_init_hook) (context, isServerStart);
140 
141  /* used by the callback */
142  ssl_is_server_start = isServerStart;
143 
144  /*
145  * Load and verify server's certificate and private key
146  */
147  if (SSL_CTX_use_certificate_chain_file(context, ssl_cert_file) != 1)
148  {
149  ereport(isServerStart ? FATAL : LOG,
150  (errcode(ERRCODE_CONFIG_FILE_ERROR),
151  errmsg("could not load server certificate file \"%s\": %s",
152  ssl_cert_file, SSLerrmessage(ERR_get_error()))));
153  goto error;
154  }
155 
156  if (!check_ssl_key_file_permissions(ssl_key_file, isServerStart))
157  goto error;
158 
159  /*
160  * OK, try to load the private key file.
161  */
163 
164  if (SSL_CTX_use_PrivateKey_file(context,
165  ssl_key_file,
166  SSL_FILETYPE_PEM) != 1)
167  {
169  ereport(isServerStart ? FATAL : LOG,
170  (errcode(ERRCODE_CONFIG_FILE_ERROR),
171  errmsg("private key file \"%s\" cannot be reloaded because it requires a passphrase",
172  ssl_key_file)));
173  else
174  ereport(isServerStart ? FATAL : LOG,
175  (errcode(ERRCODE_CONFIG_FILE_ERROR),
176  errmsg("could not load private key file \"%s\": %s",
177  ssl_key_file, SSLerrmessage(ERR_get_error()))));
178  goto error;
179  }
180 
181  if (SSL_CTX_check_private_key(context) != 1)
182  {
183  ereport(isServerStart ? FATAL : LOG,
184  (errcode(ERRCODE_CONFIG_FILE_ERROR),
185  errmsg("check of private key failed: %s",
186  SSLerrmessage(ERR_get_error()))));
187  goto error;
188  }
189 
191  {
193 
194  if (ssl_ver_min == -1)
195  {
196  ereport(isServerStart ? FATAL : LOG,
197  /*- translator: first %s is a GUC option name, second %s is its value */
198  (errmsg("\"%s\" setting \"%s\" not supported by this build",
199  "ssl_min_protocol_version",
200  GetConfigOption("ssl_min_protocol_version",
201  false, false))));
202  goto error;
203  }
204 
205  if (!SSL_CTX_set_min_proto_version(context, ssl_ver_min))
206  {
207  ereport(isServerStart ? FATAL : LOG,
208  (errmsg("could not set minimum SSL protocol version")));
209  goto error;
210  }
211  }
212 
214  {
216 
217  if (ssl_ver_max == -1)
218  {
219  ereport(isServerStart ? FATAL : LOG,
220  /*- translator: first %s is a GUC option name, second %s is its value */
221  (errmsg("\"%s\" setting \"%s\" not supported by this build",
222  "ssl_max_protocol_version",
223  GetConfigOption("ssl_max_protocol_version",
224  false, false))));
225  goto error;
226  }
227 
228  if (!SSL_CTX_set_max_proto_version(context, ssl_ver_max))
229  {
230  ereport(isServerStart ? FATAL : LOG,
231  (errmsg("could not set maximum SSL protocol version")));
232  goto error;
233  }
234  }
235 
236  /* Check compatibility of min/max protocols */
239  {
240  /*
241  * No need to check for invalid values (-1) for each protocol number
242  * as the code above would have already generated an error.
243  */
244  if (ssl_ver_min > ssl_ver_max)
245  {
246  ereport(isServerStart ? FATAL : LOG,
247  (errmsg("could not set SSL protocol version range"),
248  errdetail("\"%s\" cannot be higher than \"%s\"",
249  "ssl_min_protocol_version",
250  "ssl_max_protocol_version")));
251  goto error;
252  }
253  }
254 
255  /* disallow SSL session tickets */
256  SSL_CTX_set_options(context, SSL_OP_NO_TICKET);
257 
258  /* disallow SSL session caching, too */
259  SSL_CTX_set_session_cache_mode(context, SSL_SESS_CACHE_OFF);
260 
261  /* disallow SSL compression */
262  SSL_CTX_set_options(context, SSL_OP_NO_COMPRESSION);
263 
264 #ifdef SSL_OP_NO_RENEGOTIATION
265 
266  /*
267  * Disallow SSL renegotiation, option available since 1.1.0h. This
268  * concerns only TLSv1.2 and older protocol versions, as TLSv1.3 has no
269  * support for renegotiation.
270  */
271  SSL_CTX_set_options(context, SSL_OP_NO_RENEGOTIATION);
272 #endif
273 
274  /* set up ephemeral DH and ECDH keys */
275  if (!initialize_dh(context, isServerStart))
276  goto error;
277  if (!initialize_ecdh(context, isServerStart))
278  goto error;
279 
280  /* set up the allowed cipher list */
281  if (SSL_CTX_set_cipher_list(context, SSLCipherSuites) != 1)
282  {
283  ereport(isServerStart ? FATAL : LOG,
284  (errcode(ERRCODE_CONFIG_FILE_ERROR),
285  errmsg("could not set the cipher list (no valid ciphers available)")));
286  goto error;
287  }
288 
289  /* Let server choose order */
291  SSL_CTX_set_options(context, SSL_OP_CIPHER_SERVER_PREFERENCE);
292 
293  /*
294  * Load CA store, so we can verify client certificates if needed.
295  */
296  if (ssl_ca_file[0])
297  {
298  STACK_OF(X509_NAME) * root_cert_list;
299 
300  if (SSL_CTX_load_verify_locations(context, ssl_ca_file, NULL) != 1 ||
301  (root_cert_list = SSL_load_client_CA_file(ssl_ca_file)) == NULL)
302  {
303  ereport(isServerStart ? FATAL : LOG,
304  (errcode(ERRCODE_CONFIG_FILE_ERROR),
305  errmsg("could not load root certificate file \"%s\": %s",
306  ssl_ca_file, SSLerrmessage(ERR_get_error()))));
307  goto error;
308  }
309 
310  /*
311  * Tell OpenSSL to send the list of root certs we trust to clients in
312  * CertificateRequests. This lets a client with a keystore select the
313  * appropriate client certificate to send to us. Also, this ensures
314  * that the SSL context will "own" the root_cert_list and remember to
315  * free it when no longer needed.
316  */
317  SSL_CTX_set_client_CA_list(context, root_cert_list);
318 
319  /*
320  * Always ask for SSL client cert, but don't fail if it's not
321  * presented. We might fail such connections later, depending on what
322  * we find in pg_hba.conf.
323  */
324  SSL_CTX_set_verify(context,
325  (SSL_VERIFY_PEER |
326  SSL_VERIFY_CLIENT_ONCE),
327  verify_cb);
328  }
329 
330  /*----------
331  * Load the Certificate Revocation List (CRL).
332  * http://searchsecurity.techtarget.com/sDefinition/0,,sid14_gci803160,00.html
333  *----------
334  */
335  if (ssl_crl_file[0] || ssl_crl_dir[0])
336  {
337  X509_STORE *cvstore = SSL_CTX_get_cert_store(context);
338 
339  if (cvstore)
340  {
341  /* Set the flags to check against the complete CRL chain */
342  if (X509_STORE_load_locations(cvstore,
343  ssl_crl_file[0] ? ssl_crl_file : NULL,
344  ssl_crl_dir[0] ? ssl_crl_dir : NULL)
345  == 1)
346  {
347  X509_STORE_set_flags(cvstore,
348  X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
349  }
350  else if (ssl_crl_dir[0] == 0)
351  {
352  ereport(isServerStart ? FATAL : LOG,
353  (errcode(ERRCODE_CONFIG_FILE_ERROR),
354  errmsg("could not load SSL certificate revocation list file \"%s\": %s",
355  ssl_crl_file, SSLerrmessage(ERR_get_error()))));
356  goto error;
357  }
358  else if (ssl_crl_file[0] == 0)
359  {
360  ereport(isServerStart ? FATAL : LOG,
361  (errcode(ERRCODE_CONFIG_FILE_ERROR),
362  errmsg("could not load SSL certificate revocation list directory \"%s\": %s",
363  ssl_crl_dir, SSLerrmessage(ERR_get_error()))));
364  goto error;
365  }
366  else
367  {
368  ereport(isServerStart ? FATAL : LOG,
369  (errcode(ERRCODE_CONFIG_FILE_ERROR),
370  errmsg("could not load SSL certificate revocation list file \"%s\" or directory \"%s\": %s",
372  SSLerrmessage(ERR_get_error()))));
373  goto error;
374  }
375  }
376  }
377 
378  /*
379  * Success! Replace any existing SSL_context.
380  */
381  if (SSL_context)
382  SSL_CTX_free(SSL_context);
383 
384  SSL_context = context;
385 
386  /*
387  * Set flag to remember whether CA store has been loaded into SSL_context.
388  */
389  if (ssl_ca_file[0])
390  ssl_loaded_verify_locations = true;
391  else
392  ssl_loaded_verify_locations = false;
393 
394  return 0;
395 
396  /* Clean up by releasing working context. */
397 error:
398  if (context)
399  SSL_CTX_free(context);
400  return -1;
401 }
bool check_ssl_key_file_permissions(const char *ssl_key_file, bool isServerStart)
static const char * SSLerrmessage(unsigned long ecode)
static int ssl_protocol_version_to_openssl(int v)
static bool initialize_dh(SSL_CTX *context, bool isServerStart)
static bool ssl_is_server_start
static bool SSL_initialized
static int verify_cb(int ok, X509_STORE_CTX *ctx)
static bool initialize_ecdh(SSL_CTX *context, bool isServerStart)
static bool dummy_ssl_passwd_cb_called
char * ssl_crl_dir
Definition: be-secure.c:43
int ssl_min_protocol_version
Definition: be-secure.c:61
char * ssl_cert_file
Definition: be-secure.c:39
bool SSLPreferServerCiphers
Definition: be-secure.c:59
int ssl_max_protocol_version
Definition: be-secure.c:62
char * SSLCipherSuites
Definition: be-secure.c:53
char * ssl_key_file
Definition: be-secure.c:40
char * ssl_crl_file
Definition: be-secure.c:42
char * ssl_ca_file
Definition: be-secure.c:41
int errdetail(const char *fmt,...)
Definition: elog.c:1039
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define LOG
Definition: elog.h:27
#define FATAL
Definition: elog.h:37
#define ereport(elevel,...)
Definition: elog.h:145
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4182
int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, int version)
int SSL_CTX_set_min_proto_version(SSL_CTX *ctx, int version)
static void error(void)
Definition: sql-dyntest.c:147

References check_ssl_key_file_permissions(), dummy_ssl_passwd_cb_called, ereport, errcode(), errdetail(), errmsg(), error(), FATAL, GetConfigOption(), initialize_dh(), initialize_ecdh(), LOG, ssl_ca_file, ssl_cert_file, SSL_context, ssl_crl_dir, ssl_crl_file, SSL_CTX_set_max_proto_version(), SSL_CTX_set_min_proto_version(), SSL_initialized, ssl_is_server_start, ssl_key_file, ssl_max_protocol_version, ssl_min_protocol_version, ssl_protocol_version_to_openssl(), SSLCipherSuites, SSLerrmessage(), SSLPreferServerCiphers, and verify_cb().

Referenced by secure_initialize().

◆ be_tls_open_server()

int be_tls_open_server ( Port port)

Definition at line 413 of file be-secure-openssl.c.

414 {
415  int r;
416  int err;
417  int waitfor;
418  unsigned long ecode;
419  bool give_proto_hint;
420 
421  Assert(!port->ssl);
422  Assert(!port->peer);
423 
424  if (!SSL_context)
425  {
427  (errcode(ERRCODE_PROTOCOL_VIOLATION),
428  errmsg("could not initialize SSL connection: SSL context not set up")));
429  return -1;
430  }
431 
432  /* set up debugging/info callback */
433  SSL_CTX_set_info_callback(SSL_context, info_cb);
434 
435  if (!(port->ssl = SSL_new(SSL_context)))
436  {
438  (errcode(ERRCODE_PROTOCOL_VIOLATION),
439  errmsg("could not initialize SSL connection: %s",
440  SSLerrmessage(ERR_get_error()))));
441  return -1;
442  }
443  if (!my_SSL_set_fd(port, port->sock))
444  {
446  (errcode(ERRCODE_PROTOCOL_VIOLATION),
447  errmsg("could not set SSL socket: %s",
448  SSLerrmessage(ERR_get_error()))));
449  return -1;
450  }
451  port->ssl_in_use = true;
452 
453 aloop:
454 
455  /*
456  * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
457  * queue. In general, the current thread's error queue must be empty
458  * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
459  * not work reliably. An extension may have failed to clear the
460  * per-thread error queue following another call to an OpenSSL I/O
461  * routine.
462  */
463  ERR_clear_error();
464  r = SSL_accept(port->ssl);
465  if (r <= 0)
466  {
467  err = SSL_get_error(port->ssl, r);
468 
469  /*
470  * Other clients of OpenSSL in the backend may fail to call
471  * ERR_get_error(), but we always do, so as to not cause problems for
472  * OpenSSL clients that don't call ERR_clear_error() defensively. Be
473  * sure that this happens by calling now. SSL_get_error() relies on
474  * the OpenSSL per-thread error queue being intact, so this is the
475  * earliest possible point ERR_get_error() may be called.
476  */
477  ecode = ERR_get_error();
478  switch (err)
479  {
480  case SSL_ERROR_WANT_READ:
481  case SSL_ERROR_WANT_WRITE:
482  /* not allowed during connection establishment */
483  Assert(!port->noblock);
484 
485  /*
486  * No need to care about timeouts/interrupts here. At this
487  * point authentication_timeout still employs
488  * StartupPacketTimeoutHandler() which directly exits.
489  */
490  if (err == SSL_ERROR_WANT_READ)
492  else
494 
495  (void) WaitLatchOrSocket(MyLatch, waitfor, port->sock, 0,
497  goto aloop;
498  case SSL_ERROR_SYSCALL:
499  if (r < 0)
502  errmsg("could not accept SSL connection: %m")));
503  else
505  (errcode(ERRCODE_PROTOCOL_VIOLATION),
506  errmsg("could not accept SSL connection: EOF detected")));
507  break;
508  case SSL_ERROR_SSL:
509  switch (ERR_GET_REASON(ecode))
510  {
511  /*
512  * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
513  * TLSV1_ALERT_PROTOCOL_VERSION have been observed
514  * when trying to communicate with an old OpenSSL
515  * library, or when the client and server specify
516  * disjoint protocol ranges. NO_PROTOCOLS_AVAILABLE
517  * occurs if there's a local misconfiguration (which
518  * can happen despite our checks, if openssl.cnf
519  * injects a limit we didn't account for). It's not
520  * very clear what would make OpenSSL return the other
521  * codes listed here, but a hint about protocol
522  * versions seems like it's appropriate for all.
523  */
524  case SSL_R_NO_PROTOCOLS_AVAILABLE:
525  case SSL_R_UNSUPPORTED_PROTOCOL:
526  case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
527  case SSL_R_UNKNOWN_PROTOCOL:
528  case SSL_R_UNKNOWN_SSL_VERSION:
529  case SSL_R_UNSUPPORTED_SSL_VERSION:
530  case SSL_R_WRONG_SSL_VERSION:
531  case SSL_R_WRONG_VERSION_NUMBER:
532  case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
533 #ifdef SSL_R_VERSION_TOO_HIGH
534  case SSL_R_VERSION_TOO_HIGH:
535  case SSL_R_VERSION_TOO_LOW:
536 #endif
537  give_proto_hint = true;
538  break;
539  default:
540  give_proto_hint = false;
541  break;
542  }
544  (errcode(ERRCODE_PROTOCOL_VIOLATION),
545  errmsg("could not accept SSL connection: %s",
546  SSLerrmessage(ecode)),
548  give_proto_hint ?
549  errhint("This may indicate that the client does not support any SSL protocol version between %s and %s.",
552  MIN_OPENSSL_TLS_VERSION,
555  MAX_OPENSSL_TLS_VERSION) : 0));
556  cert_errdetail = NULL;
557  break;
558  case SSL_ERROR_ZERO_RETURN:
560  (errcode(ERRCODE_PROTOCOL_VIOLATION),
561  errmsg("could not accept SSL connection: EOF detected")));
562  break;
563  default:
565  (errcode(ERRCODE_PROTOCOL_VIOLATION),
566  errmsg("unrecognized SSL error code: %d",
567  err)));
568  break;
569  }
570  return -1;
571  }
572 
573  /* Get client certificate, if available. */
574  port->peer = SSL_get_peer_certificate(port->ssl);
575 
576  /* and extract the Common Name and Distinguished Name from it. */
577  port->peer_cn = NULL;
578  port->peer_dn = NULL;
579  port->peer_cert_valid = false;
580  if (port->peer != NULL)
581  {
582  int len;
583  X509_NAME *x509name = X509_get_subject_name(port->peer);
584  char *peer_dn;
585  BIO *bio = NULL;
586  BUF_MEM *bio_buf = NULL;
587 
588  len = X509_NAME_get_text_by_NID(x509name, NID_commonName, NULL, 0);
589  if (len != -1)
590  {
591  char *peer_cn;
592 
593  peer_cn = MemoryContextAlloc(TopMemoryContext, len + 1);
594  r = X509_NAME_get_text_by_NID(x509name, NID_commonName, peer_cn,
595  len + 1);
596  peer_cn[len] = '\0';
597  if (r != len)
598  {
599  /* shouldn't happen */
600  pfree(peer_cn);
601  return -1;
602  }
603 
604  /*
605  * Reject embedded NULLs in certificate common name to prevent
606  * attacks like CVE-2009-4034.
607  */
608  if (len != strlen(peer_cn))
609  {
611  (errcode(ERRCODE_PROTOCOL_VIOLATION),
612  errmsg("SSL certificate's common name contains embedded null")));
613  pfree(peer_cn);
614  return -1;
615  }
616 
617  port->peer_cn = peer_cn;
618  }
619 
620  bio = BIO_new(BIO_s_mem());
621  if (!bio)
622  {
623  pfree(port->peer_cn);
624  port->peer_cn = NULL;
625  return -1;
626  }
627 
628  /*
629  * RFC2253 is the closest thing to an accepted standard format for
630  * DNs. We have documented how to produce this format from a
631  * certificate. It uses commas instead of slashes for delimiters,
632  * which make regular expression matching a bit easier. Also note that
633  * it prints the Subject fields in reverse order.
634  */
635  X509_NAME_print_ex(bio, x509name, 0, XN_FLAG_RFC2253);
636  if (BIO_get_mem_ptr(bio, &bio_buf) <= 0)
637  {
638  BIO_free(bio);
639  pfree(port->peer_cn);
640  port->peer_cn = NULL;
641  return -1;
642  }
643  peer_dn = MemoryContextAlloc(TopMemoryContext, bio_buf->length + 1);
644  memcpy(peer_dn, bio_buf->data, bio_buf->length);
645  len = bio_buf->length;
646  BIO_free(bio);
647  peer_dn[len] = '\0';
648  if (len != strlen(peer_dn))
649  {
651  (errcode(ERRCODE_PROTOCOL_VIOLATION),
652  errmsg("SSL certificate's distinguished name contains embedded null")));
653  pfree(peer_dn);
654  pfree(port->peer_cn);
655  port->peer_cn = NULL;
656  return -1;
657  }
658 
659  port->peer_dn = peer_dn;
660 
661  port->peer_cert_valid = true;
662  }
663 
664  return 0;
665 }
static const char * ssl_protocol_version_to_string(int v)
static const char * cert_errdetail
static void info_cb(const SSL *ssl, int type, int args)
static int my_SSL_set_fd(Port *port, int fd)
int errcode_for_socket_access(void)
Definition: elog.c:789
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1066
int errhint(const char *fmt,...)
Definition: elog.c:1153
#define COMMERROR
Definition: elog.h:29
struct Latch * MyLatch
Definition: globals.c:58
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:524
#define WL_SOCKET_READABLE
Definition: latch.h:126
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_SOCKET_WRITEABLE
Definition: latch.h:127
Assert(fmt[strlen(fmt) - 1] !='\n')
MemoryContext TopMemoryContext
Definition: mcxt.c:130
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:994
@ WAIT_EVENT_SSL_OPEN_SERVER
Definition: wait_event.h:67

References Assert(), cert_errdetail, COMMERROR, ereport, errcode(), errcode_for_socket_access(), errdetail_internal(), errhint(), errmsg(), info_cb(), len, MemoryContextAlloc(), my_SSL_set_fd(), MyLatch, pfree(), port, SSL_context, ssl_max_protocol_version, ssl_min_protocol_version, ssl_protocol_version_to_string(), SSLerrmessage(), TopMemoryContext, WAIT_EVENT_SSL_OPEN_SERVER, WaitLatchOrSocket(), WL_EXIT_ON_PM_DEATH, WL_SOCKET_READABLE, and WL_SOCKET_WRITEABLE.

Referenced by secure_open_server().

◆ be_tls_read()

ssize_t be_tls_read ( Port port,
void *  ptr,
size_t  len,
int *  waitfor 
)

Definition at line 698 of file be-secure-openssl.c.

699 {
700  ssize_t n;
701  int err;
702  unsigned long ecode;
703 
704  errno = 0;
705  ERR_clear_error();
706  n = SSL_read(port->ssl, ptr, len);
707  err = SSL_get_error(port->ssl, n);
708  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
709  switch (err)
710  {
711  case SSL_ERROR_NONE:
712  /* a-ok */
713  break;
714  case SSL_ERROR_WANT_READ:
715  *waitfor = WL_SOCKET_READABLE;
716  errno = EWOULDBLOCK;
717  n = -1;
718  break;
719  case SSL_ERROR_WANT_WRITE:
720  *waitfor = WL_SOCKET_WRITEABLE;
721  errno = EWOULDBLOCK;
722  n = -1;
723  break;
724  case SSL_ERROR_SYSCALL:
725  /* leave it to caller to ereport the value of errno */
726  if (n != -1)
727  {
728  errno = ECONNRESET;
729  n = -1;
730  }
731  break;
732  case SSL_ERROR_SSL:
734  (errcode(ERRCODE_PROTOCOL_VIOLATION),
735  errmsg("SSL error: %s", SSLerrmessage(ecode))));
736  errno = ECONNRESET;
737  n = -1;
738  break;
739  case SSL_ERROR_ZERO_RETURN:
740  /* connection was cleanly shut down by peer */
741  n = 0;
742  break;
743  default:
745  (errcode(ERRCODE_PROTOCOL_VIOLATION),
746  errmsg("unrecognized SSL error code: %d",
747  err)));
748  errno = ECONNRESET;
749  n = -1;
750  break;
751  }
752 
753  return n;
754 }
#define EWOULDBLOCK
Definition: win32_port.h:375
#define ECONNRESET
Definition: win32_port.h:379

References COMMERROR, ECONNRESET, ereport, errcode(), errmsg(), EWOULDBLOCK, len, port, SSLerrmessage(), WL_SOCKET_READABLE, and WL_SOCKET_WRITEABLE.

Referenced by secure_read().

◆ be_tls_write()

ssize_t be_tls_write ( Port port,
void *  ptr,
size_t  len,
int *  waitfor 
)

Definition at line 757 of file be-secure-openssl.c.

758 {
759  ssize_t n;
760  int err;
761  unsigned long ecode;
762 
763  errno = 0;
764  ERR_clear_error();
765  n = SSL_write(port->ssl, ptr, len);
766  err = SSL_get_error(port->ssl, n);
767  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
768  switch (err)
769  {
770  case SSL_ERROR_NONE:
771  /* a-ok */
772  break;
773  case SSL_ERROR_WANT_READ:
774  *waitfor = WL_SOCKET_READABLE;
775  errno = EWOULDBLOCK;
776  n = -1;
777  break;
778  case SSL_ERROR_WANT_WRITE:
779  *waitfor = WL_SOCKET_WRITEABLE;
780  errno = EWOULDBLOCK;
781  n = -1;
782  break;
783  case SSL_ERROR_SYSCALL:
784  /* leave it to caller to ereport the value of errno */
785  if (n != -1)
786  {
787  errno = ECONNRESET;
788  n = -1;
789  }
790  break;
791  case SSL_ERROR_SSL:
793  (errcode(ERRCODE_PROTOCOL_VIOLATION),
794  errmsg("SSL error: %s", SSLerrmessage(ecode))));
795  errno = ECONNRESET;
796  n = -1;
797  break;
798  case SSL_ERROR_ZERO_RETURN:
799 
800  /*
801  * the SSL connection was closed, leave it to the caller to
802  * ereport it
803  */
804  errno = ECONNRESET;
805  n = -1;
806  break;
807  default:
809  (errcode(ERRCODE_PROTOCOL_VIOLATION),
810  errmsg("unrecognized SSL error code: %d",
811  err)));
812  errno = ECONNRESET;
813  n = -1;
814  break;
815  }
816 
817  return n;
818 }

References COMMERROR, ECONNRESET, ereport, errcode(), errmsg(), EWOULDBLOCK, len, port, SSLerrmessage(), WL_SOCKET_READABLE, and WL_SOCKET_WRITEABLE.

Referenced by secure_write().

◆ default_openssl_tls_init()

static void default_openssl_tls_init ( SSL_CTX *  context,
bool  isServerStart 
)
static

Definition at line 1621 of file be-secure-openssl.c.

1622 {
1623  if (isServerStart)
1624  {
1625  if (ssl_passphrase_command[0])
1626  SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
1627  }
1628  else
1629  {
1631  SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
1632  else
1633 
1634  /*
1635  * If reloading and no external command is configured, override
1636  * OpenSSL's default handling of passphrase-protected files,
1637  * because we don't want to prompt for a passphrase in an
1638  * already-running server.
1639  */
1640  SSL_CTX_set_default_passwd_cb(context, dummy_ssl_passwd_cb);
1641  }
1642 }
static int dummy_ssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
static int ssl_external_passwd_cb(char *buf, int size, int rwflag, void *userdata)
char * ssl_passphrase_command
Definition: be-secure.c:45
bool ssl_passphrase_command_supports_reload
Definition: be-secure.c:46

References dummy_ssl_passwd_cb(), ssl_external_passwd_cb(), ssl_passphrase_command, and ssl_passphrase_command_supports_reload.

◆ dummy_ssl_passwd_cb()

static int dummy_ssl_passwd_cb ( char *  buf,
int  size,
int  rwflag,
void *  userdata 
)
static

Definition at line 1074 of file be-secure-openssl.c.

1075 {
1076  /* Set flag to change the error message we'll report */
1078  /* And return empty string */
1079  Assert(size > 0);
1080  buf[0] = '\0';
1081  return 0;
1082 }
static char * buf
Definition: pg_test_fsync.c:67

References Assert(), buf, and dummy_ssl_passwd_cb_called.

Referenced by default_openssl_tls_init().

◆ info_cb()

static void info_cb ( const SSL *  ssl,
int  type,
int  args 
)
static

Definition at line 1210 of file be-secure-openssl.c.

1211 {
1212  const char *desc;
1213 
1214  desc = SSL_state_string_long(ssl);
1215 
1216  switch (type)
1217  {
1218  case SSL_CB_HANDSHAKE_START:
1219  ereport(DEBUG4,
1220  (errmsg_internal("SSL: handshake start: \"%s\"", desc)));
1221  break;
1222  case SSL_CB_HANDSHAKE_DONE:
1223  ereport(DEBUG4,
1224  (errmsg_internal("SSL: handshake done: \"%s\"", desc)));
1225  break;
1226  case SSL_CB_ACCEPT_LOOP:
1227  ereport(DEBUG4,
1228  (errmsg_internal("SSL: accept loop: \"%s\"", desc)));
1229  break;
1230  case SSL_CB_ACCEPT_EXIT:
1231  ereport(DEBUG4,
1232  (errmsg_internal("SSL: accept exit (%d): \"%s\"", args, desc)));
1233  break;
1234  case SSL_CB_CONNECT_LOOP:
1235  ereport(DEBUG4,
1236  (errmsg_internal("SSL: connect loop: \"%s\"", desc)));
1237  break;
1238  case SSL_CB_CONNECT_EXIT:
1239  ereport(DEBUG4,
1240  (errmsg_internal("SSL: connect exit (%d): \"%s\"", args, desc)));
1241  break;
1242  case SSL_CB_READ_ALERT:
1243  ereport(DEBUG4,
1244  (errmsg_internal("SSL: read alert (0x%04x): \"%s\"", args, desc)));
1245  break;
1246  case SSL_CB_WRITE_ALERT:
1247  ereport(DEBUG4,
1248  (errmsg_internal("SSL: write alert (0x%04x): \"%s\"", args, desc)));
1249  break;
1250  }
1251 }
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
#define DEBUG4
Definition: elog.h:23

References generate_unaccent_rules::args, DEBUG4, ereport, errmsg_internal(), and generate_unaccent_rules::type.

Referenced by be_tls_open_server().

◆ initialize_dh()

static bool initialize_dh ( SSL_CTX *  context,
bool  isServerStart 
)
static

Definition at line 1267 of file be-secure-openssl.c.

1268 {
1269  DH *dh = NULL;
1270 
1271  SSL_CTX_set_options(context, SSL_OP_SINGLE_DH_USE);
1272 
1273  if (ssl_dh_params_file[0])
1274  dh = load_dh_file(ssl_dh_params_file, isServerStart);
1275  if (!dh)
1276  dh = load_dh_buffer(FILE_DH2048, sizeof(FILE_DH2048));
1277  if (!dh)
1278  {
1279  ereport(isServerStart ? FATAL : LOG,
1280  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1281  errmsg("DH: could not load DH parameters")));
1282  return false;
1283  }
1284 
1285  if (SSL_CTX_set_tmp_dh(context, dh) != 1)
1286  {
1287  ereport(isServerStart ? FATAL : LOG,
1288  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1289  errmsg("DH: could not set DH parameters: %s",
1290  SSLerrmessage(ERR_get_error()))));
1291  DH_free(dh);
1292  return false;
1293  }
1294 
1295  DH_free(dh);
1296  return true;
1297 }
static DH * load_dh_buffer(const char *buffer, size_t len)
static DH * load_dh_file(char *filename, bool isServerStart)
char * ssl_dh_params_file
Definition: be-secure.c:44

References ereport, errcode(), errmsg(), FATAL, load_dh_buffer(), load_dh_file(), LOG, ssl_dh_params_file, and SSLerrmessage().

Referenced by be_tls_init().

◆ initialize_ecdh()

static bool initialize_ecdh ( SSL_CTX *  context,
bool  isServerStart 
)
static

Definition at line 1305 of file be-secure-openssl.c.

1306 {
1307 #ifndef OPENSSL_NO_ECDH
1308  EC_KEY *ecdh;
1309  int nid;
1310 
1311  nid = OBJ_sn2nid(SSLECDHCurve);
1312  if (!nid)
1313  {
1314  ereport(isServerStart ? FATAL : LOG,
1315  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1316  errmsg("ECDH: unrecognized curve name: %s", SSLECDHCurve)));
1317  return false;
1318  }
1319 
1320  ecdh = EC_KEY_new_by_curve_name(nid);
1321  if (!ecdh)
1322  {
1323  ereport(isServerStart ? FATAL : LOG,
1324  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1325  errmsg("ECDH: could not create key")));
1326  return false;
1327  }
1328 
1329  SSL_CTX_set_options(context, SSL_OP_SINGLE_ECDH_USE);
1330  SSL_CTX_set_tmp_ecdh(context, ecdh);
1331  EC_KEY_free(ecdh);
1332 #endif
1333 
1334  return true;
1335 }
char * SSLECDHCurve
Definition: be-secure.c:56

References ereport, errcode(), errmsg(), FATAL, LOG, and SSLECDHCurve.

Referenced by be_tls_init().

◆ load_dh_buffer()

static DH * load_dh_buffer ( const char *  buffer,
size_t  len 
)
static

Definition at line 1032 of file be-secure-openssl.c.

1033 {
1034  BIO *bio;
1035  DH *dh = NULL;
1036 
1037  bio = BIO_new_mem_buf(unconstify(char *, buffer), len);
1038  if (bio == NULL)
1039  return NULL;
1040  dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
1041  if (dh == NULL)
1042  ereport(DEBUG2,
1043  (errmsg_internal("DH load buffer: %s",
1044  SSLerrmessage(ERR_get_error()))));
1045  BIO_free(bio);
1046 
1047  return dh;
1048 }
#define unconstify(underlying_type, expr)
Definition: c.h:1181
#define DEBUG2
Definition: elog.h:25

References DEBUG2, ereport, errmsg_internal(), len, SSLerrmessage(), and unconstify.

Referenced by initialize_dh().

◆ load_dh_file()

static DH * load_dh_file ( char *  filename,
bool  isServerStart 
)
static

Definition at line 965 of file be-secure-openssl.c.

966 {
967  FILE *fp;
968  DH *dh = NULL;
969  int codes;
970 
971  /* attempt to open file. It's not an error if it doesn't exist. */
972  if ((fp = AllocateFile(filename, "r")) == NULL)
973  {
974  ereport(isServerStart ? FATAL : LOG,
976  errmsg("could not open DH parameters file \"%s\": %m",
977  filename)));
978  return NULL;
979  }
980 
981  dh = PEM_read_DHparams(fp, NULL, NULL, NULL);
982  FreeFile(fp);
983 
984  if (dh == NULL)
985  {
986  ereport(isServerStart ? FATAL : LOG,
987  (errcode(ERRCODE_CONFIG_FILE_ERROR),
988  errmsg("could not load DH parameters file: %s",
989  SSLerrmessage(ERR_get_error()))));
990  return NULL;
991  }
992 
993  /* make sure the DH parameters are usable */
994  if (DH_check(dh, &codes) == 0)
995  {
996  ereport(isServerStart ? FATAL : LOG,
997  (errcode(ERRCODE_CONFIG_FILE_ERROR),
998  errmsg("invalid DH parameters: %s",
999  SSLerrmessage(ERR_get_error()))));
1000  DH_free(dh);
1001  return NULL;
1002  }
1003  if (codes & DH_CHECK_P_NOT_PRIME)
1004  {
1005  ereport(isServerStart ? FATAL : LOG,
1006  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1007  errmsg("invalid DH parameters: p is not prime")));
1008  DH_free(dh);
1009  return NULL;
1010  }
1011  if ((codes & DH_NOT_SUITABLE_GENERATOR) &&
1012  (codes & DH_CHECK_P_NOT_SAFE_PRIME))
1013  {
1014  ereport(isServerStart ? FATAL : LOG,
1015  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1016  errmsg("invalid DH parameters: neither suitable generator or safe prime")));
1017  DH_free(dh);
1018  return NULL;
1019  }
1020 
1021  return dh;
1022 }
int errcode_for_file_access(void)
Definition: elog.c:718
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2383
int FreeFile(FILE *file)
Definition: fd.c:2581
static char * filename
Definition: pg_dumpall.c:119

References AllocateFile(), ereport, errcode(), errcode_for_file_access(), errmsg(), FATAL, filename, FreeFile(), LOG, and SSLerrmessage().

Referenced by initialize_dh().

◆ my_BIO_s_socket()

static BIO_METHOD * my_BIO_s_socket ( void  )
static

Definition at line 887 of file be-secure-openssl.c.

888 {
889  if (!my_bio_methods)
890  {
891  BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
892 #ifdef HAVE_BIO_METH_NEW
893  int my_bio_index;
894 
895  my_bio_index = BIO_get_new_index();
896  if (my_bio_index == -1)
897  return NULL;
898  my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
899  my_bio_methods = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
900  if (!my_bio_methods)
901  return NULL;
902  if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
903  !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
904  !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
905  !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
906  !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
907  !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
908  !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
909  !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
910  {
911  BIO_meth_free(my_bio_methods);
912  my_bio_methods = NULL;
913  return NULL;
914  }
915 #else
916  my_bio_methods = malloc(sizeof(BIO_METHOD));
917  if (!my_bio_methods)
918  return NULL;
919  memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
920  my_bio_methods->bread = my_sock_read;
921  my_bio_methods->bwrite = my_sock_write;
922 #endif
923  }
924  return my_bio_methods;
925 }
static BIO_METHOD * my_bio_methods
static int my_sock_write(BIO *h, const char *buf, int size)
static int my_sock_read(BIO *h, char *buf, int size)
#define malloc(a)
Definition: header.h:50

References malloc, my_bio_methods, my_sock_read(), and my_sock_write().

Referenced by my_SSL_set_fd().

◆ my_sock_read()

static int my_sock_read ( BIO *  h,
char *  buf,
int  size 
)
static

Definition at line 846 of file be-secure-openssl.c.

847 {
848  int res = 0;
849 
850  if (buf != NULL)
851  {
852  res = secure_raw_read(((Port *) BIO_get_data(h)), buf, size);
853  BIO_clear_retry_flags(h);
854  if (res <= 0)
855  {
856  /* If we were interrupted, tell caller to retry */
857  if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
858  {
859  BIO_set_retry_read(h);
860  }
861  }
862  }
863 
864  return res;
865 }
#define BIO_get_data(bio)
ssize_t secure_raw_read(Port *port, void *ptr, size_t len)
Definition: be-secure.c:234
Definition: libpq-be.h:146
#define EINTR
Definition: win32_port.h:369
#define EAGAIN
Definition: win32_port.h:367

References BIO_get_data, buf, EAGAIN, EINTR, EWOULDBLOCK, res, and secure_raw_read().

Referenced by my_BIO_s_socket().

◆ my_sock_write()

static int my_sock_write ( BIO *  h,
const char *  buf,
int  size 
)
static

Definition at line 868 of file be-secure-openssl.c.

869 {
870  int res = 0;
871 
872  res = secure_raw_write(((Port *) BIO_get_data(h)), buf, size);
873  BIO_clear_retry_flags(h);
874  if (res <= 0)
875  {
876  /* If we were interrupted, tell caller to retry */
877  if (errno == EINTR || errno == EWOULDBLOCK || errno == EAGAIN)
878  {
879  BIO_set_retry_write(h);
880  }
881  }
882 
883  return res;
884 }
ssize_t secure_raw_write(Port *port, const void *ptr, size_t len)
Definition: be-secure.c:330

References BIO_get_data, buf, EAGAIN, EINTR, EWOULDBLOCK, res, and secure_raw_write().

Referenced by my_BIO_s_socket().

◆ my_SSL_set_fd()

static int my_SSL_set_fd ( Port port,
int  fd 
)
static

Definition at line 929 of file be-secure-openssl.c.

930 {
931  int ret = 0;
932  BIO *bio;
933  BIO_METHOD *bio_method;
934 
935  bio_method = my_BIO_s_socket();
936  if (bio_method == NULL)
937  {
938  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
939  goto err;
940  }
941  bio = BIO_new(bio_method);
942 
943  if (bio == NULL)
944  {
945  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
946  goto err;
947  }
948  BIO_set_data(bio, port);
949 
950  BIO_set_fd(bio, fd, BIO_NOCLOSE);
951  SSL_set_bio(port->ssl, bio, bio);
952  ret = 1;
953 err:
954  return ret;
955 }
static BIO_METHOD * my_BIO_s_socket(void)
#define BIO_set_data(bio, data)
static int fd(const char *x, int i)
Definition: preproc-init.c:105

References BIO_set_data, fd(), my_BIO_s_socket(), and port.

Referenced by be_tls_open_server().

◆ prepare_cert_name()

static char* prepare_cert_name ( char *  name)
static

Definition at line 1091 of file be-secure-openssl.c.

1092 {
1093  size_t namelen = strlen(name);
1094  char *truncated = name;
1095 
1096  /*
1097  * Common Names are 64 chars max, so for a common case where the CN is the
1098  * last field, we can still print the longest possible CN with a
1099  * 7-character prefix (".../CN=[64 chars]"), for a reasonable limit of 71
1100  * characters.
1101  */
1102 #define MAXLEN 71
1103 
1104  if (namelen > MAXLEN)
1105  {
1106  /*
1107  * Keep the end of the name, not the beginning, since the most specific
1108  * field is likely to give users the most information.
1109  */
1110  truncated = name + namelen - MAXLEN;
1111  truncated[0] = truncated[1] = truncated[2] = '.';
1112  namelen = MAXLEN;
1113  }
1114 
1115 #undef MAXLEN
1116 
1117  return pg_clean_ascii(truncated, 0);
1118 }
#define MAXLEN
const char * name
Definition: encode.c:561
char * pg_clean_ascii(const char *str, int alloc_flags)
Definition: string.c:86

References MAXLEN, name, and pg_clean_ascii().

Referenced by verify_cb().

◆ ssl_external_passwd_cb()

static int ssl_external_passwd_cb ( char *  buf,
int  size,
int  rwflag,
void *  userdata 
)
static

Definition at line 1054 of file be-secure-openssl.c.

1055 {
1056  /* same prompt as OpenSSL uses internally */
1057  const char *prompt = "Enter PEM pass phrase:";
1058 
1059  Assert(rwflag == 0);
1060 
1061  return run_ssl_passphrase_command(prompt, ssl_is_server_start, buf, size);
1062 }
int run_ssl_passphrase_command(const char *prompt, bool is_server_start, char *buf, int size)

References Assert(), buf, run_ssl_passphrase_command(), and ssl_is_server_start.

Referenced by default_openssl_tls_init().

◆ ssl_protocol_version_to_openssl()

static int ssl_protocol_version_to_openssl ( int  v)
static

Definition at line 1565 of file be-secure-openssl.c.

1566 {
1567  switch (v)
1568  {
1569  case PG_TLS_ANY:
1570  return 0;
1571  case PG_TLS1_VERSION:
1572  return TLS1_VERSION;
1573  case PG_TLS1_1_VERSION:
1574 #ifdef TLS1_1_VERSION
1575  return TLS1_1_VERSION;
1576 #else
1577  break;
1578 #endif
1579  case PG_TLS1_2_VERSION:
1580 #ifdef TLS1_2_VERSION
1581  return TLS1_2_VERSION;
1582 #else
1583  break;
1584 #endif
1585  case PG_TLS1_3_VERSION:
1586 #ifdef TLS1_3_VERSION
1587  return TLS1_3_VERSION;
1588 #else
1589  break;
1590 #endif
1591  }
1592 
1593  return -1;
1594 }
@ PG_TLS1_VERSION
Definition: libpq.h:130
@ PG_TLS1_3_VERSION
Definition: libpq.h:133
@ PG_TLS1_1_VERSION
Definition: libpq.h:131
@ PG_TLS1_2_VERSION
Definition: libpq.h:132
@ PG_TLS_ANY
Definition: libpq.h:129

References PG_TLS1_1_VERSION, PG_TLS1_2_VERSION, PG_TLS1_3_VERSION, PG_TLS1_VERSION, and PG_TLS_ANY.

Referenced by be_tls_init().

◆ ssl_protocol_version_to_string()

static const char * ssl_protocol_version_to_string ( int  v)
static

Definition at line 1600 of file be-secure-openssl.c.

1601 {
1602  switch (v)
1603  {
1604  case PG_TLS_ANY:
1605  return "any";
1606  case PG_TLS1_VERSION:
1607  return "TLSv1";
1608  case PG_TLS1_1_VERSION:
1609  return "TLSv1.1";
1610  case PG_TLS1_2_VERSION:
1611  return "TLSv1.2";
1612  case PG_TLS1_3_VERSION:
1613  return "TLSv1.3";
1614  }
1615 
1616  return "(unrecognized)";
1617 }

References PG_TLS1_1_VERSION, PG_TLS1_2_VERSION, PG_TLS1_3_VERSION, PG_TLS1_VERSION, and PG_TLS_ANY.

Referenced by be_tls_open_server().

◆ SSLerrmessage()

static const char * SSLerrmessage ( unsigned long  ecode)
static

Definition at line 1347 of file be-secure-openssl.c.

1348 {
1349  const char *errreason;
1350  static char errbuf[36];
1351 
1352  if (ecode == 0)
1353  return _("no SSL error reported");
1354  errreason = ERR_reason_error_string(ecode);
1355  if (errreason != NULL)
1356  return errreason;
1357  snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), ecode);
1358  return errbuf;
1359 }
#define _(x)
Definition: elog.c:90
#define snprintf
Definition: port.h:238

References _, and snprintf.

Referenced by be_tls_init(), be_tls_open_server(), be_tls_read(), be_tls_write(), initialize_dh(), load_dh_buffer(), and load_dh_file().

◆ verify_cb()

static int verify_cb ( int  ok,
X509_STORE_CTX *  ctx 
)
static

Definition at line 1131 of file be-secure-openssl.c.

1132 {
1133  int depth;
1134  int errcode;
1135  const char *errstring;
1137  X509 *cert;
1138 
1139  if (ok)
1140  {
1141  /* Nothing to do for the successful case. */
1142  return ok;
1143  }
1144 
1145  /* Pull all the information we have on the verification failure. */
1146  depth = X509_STORE_CTX_get_error_depth(ctx);
1147  errcode = X509_STORE_CTX_get_error(ctx);
1148  errstring = X509_verify_cert_error_string(errcode);
1149 
1150  initStringInfo(&str);
1152  _("Client certificate verification failed at depth %d: %s."),
1153  depth, errstring);
1154 
1155  cert = X509_STORE_CTX_get_current_cert(ctx);
1156  if (cert)
1157  {
1158  char *subject,
1159  *issuer;
1160  char *sub_prepared,
1161  *iss_prepared;
1162  char *serialno;
1163  ASN1_INTEGER *sn;
1164  BIGNUM *b;
1165 
1166  /*
1167  * Get the Subject and Issuer for logging, but don't let maliciously
1168  * huge certs flood the logs, and don't reflect non-ASCII bytes into it
1169  * either.
1170  */
1171  subject = X509_NAME_to_cstring(X509_get_subject_name(cert));
1172  sub_prepared = prepare_cert_name(subject);
1173  pfree(subject);
1174 
1175  issuer = X509_NAME_to_cstring(X509_get_issuer_name(cert));
1176  iss_prepared = prepare_cert_name(issuer);
1177  pfree(issuer);
1178 
1179  /*
1180  * Pull the serial number, too, in case a Subject is still ambiguous.
1181  * This mirrors be_tls_get_peer_serial().
1182  */
1183  sn = X509_get_serialNumber(cert);
1184  b = ASN1_INTEGER_to_BN(sn, NULL);
1185  serialno = BN_bn2dec(b);
1186 
1187  appendStringInfoChar(&str, '\n');
1189  _("Failed certificate data (unverified): subject \"%s\", serial number %s, issuer \"%s\"."),
1190  sub_prepared, serialno ? serialno : _("unknown"),
1191  iss_prepared);
1192 
1193  BN_free(b);
1194  OPENSSL_free(serialno);
1195  pfree(iss_prepared);
1196  pfree(sub_prepared);
1197  }
1198 
1199  /* Store our detail message to be logged later. */
1200  cert_errdetail = str.data;
1201 
1202  return ok;
1203 }
static char * prepare_cert_name(char *name)
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59

References _, appendStringInfo(), appendStringInfoChar(), b, cert_errdetail, errcode(), initStringInfo(), pfree(), prepare_cert_name(), generate_unaccent_rules::str, and X509_NAME_to_cstring().

Referenced by be_tls_init().

◆ X509_NAME_to_cstring()

static char * X509_NAME_to_cstring ( X509_NAME *  name)
static

Definition at line 1493 of file be-secure-openssl.c.

1494 {
1495  BIO *membuf = BIO_new(BIO_s_mem());
1496  int i,
1497  nid,
1498  count = X509_NAME_entry_count(name);
1499  X509_NAME_ENTRY *e;
1500  ASN1_STRING *v;
1501  const char *field_name;
1502  size_t size;
1503  char nullterm;
1504  char *sp;
1505  char *dp;
1506  char *result;
1507 
1508  if (membuf == NULL)
1509  ereport(ERROR,
1510  (errcode(ERRCODE_OUT_OF_MEMORY),
1511  errmsg("could not create BIO")));
1512 
1513  (void) BIO_set_close(membuf, BIO_CLOSE);
1514  for (i = 0; i < count; i++)
1515  {
1516  e = X509_NAME_get_entry(name, i);
1517  nid = OBJ_obj2nid(X509_NAME_ENTRY_get_object(e));
1518  if (nid == NID_undef)
1519  ereport(ERROR,
1520  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1521  errmsg("could not get NID for ASN1_OBJECT object")));
1522  v = X509_NAME_ENTRY_get_data(e);
1523  field_name = OBJ_nid2sn(nid);
1524  if (field_name == NULL)
1525  field_name = OBJ_nid2ln(nid);
1526  if (field_name == NULL)
1527  ereport(ERROR,
1528  (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1529  errmsg("could not convert NID %d to an ASN1_OBJECT structure", nid)));
1530  BIO_printf(membuf, "/%s=", field_name);
1531  ASN1_STRING_print_ex(membuf, v,
1532  ((ASN1_STRFLGS_RFC2253 & ~ASN1_STRFLGS_ESC_MSB)
1533  | ASN1_STRFLGS_UTF8_CONVERT));
1534  }
1535 
1536  /* ensure null termination of the BIO's content */
1537  nullterm = '\0';
1538  BIO_write(membuf, &nullterm, 1);
1539  size = BIO_get_mem_data(membuf, &sp);
1540  dp = pg_any_to_server(sp, size - 1, PG_UTF8);
1541 
1542  result = pstrdup(dp);
1543  if (dp != sp)
1544  pfree(dp);
1545  if (BIO_free(membuf) != 1)
1546  elog(ERROR, "could not free OpenSSL BIO structure");
1547 
1548  return result;
1549 }
#define ERROR
Definition: elog.h:35
int i
Definition: isn.c:73
char * pg_any_to_server(const char *s, int len, int encoding)
Definition: mbutils.c:676
char * pstrdup(const char *in)
Definition: mcxt.c:1483
@ PG_UTF8
Definition: pg_wchar.h:232
e
Definition: preproc-init.c:82

References elog(), ereport, errcode(), errmsg(), ERROR, i, name, pfree(), pg_any_to_server(), PG_UTF8, and pstrdup().

Referenced by be_tls_get_peer_issuer_name(), be_tls_get_peer_subject_name(), and verify_cb().

Variable Documentation

◆ cert_errdetail

const char* cert_errdetail
static

Definition at line 85 of file be-secure-openssl.c.

Referenced by be_tls_open_server(), and verify_cb().

◆ dummy_ssl_passwd_cb_called

bool dummy_ssl_passwd_cb_called = false
static

Definition at line 78 of file be-secure-openssl.c.

Referenced by be_tls_init(), and dummy_ssl_passwd_cb().

◆ my_bio_methods

BIO_METHOD* my_bio_methods = NULL
static

Definition at line 843 of file be-secure-openssl.c.

Referenced by my_BIO_s_socket().

◆ openssl_tls_init_hook

openssl_tls_init_hook_typ openssl_tls_init_hook = default_openssl_tls_init

Definition at line 57 of file be-secure-openssl.c.

Referenced by _PG_init().

◆ SSL_context

SSL_CTX* SSL_context = NULL
static

◆ SSL_initialized

bool SSL_initialized = false
static

Definition at line 77 of file be-secure-openssl.c.

Referenced by be_tls_init().

◆ ssl_is_server_start

bool ssl_is_server_start
static

Definition at line 79 of file be-secure-openssl.c.

Referenced by be_tls_init(), and ssl_external_passwd_cb().