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 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)
 
char * be_tls_get_certificate_hash (Port *port, 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

◆ MAXLEN

#define MAXLEN   71

Function Documentation

◆ be_tls_close()

void be_tls_close ( Port port)

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

678 {
679  if (port->ssl)
680  {
681  SSL_shutdown(port->ssl);
682  SSL_free(port->ssl);
683  port->ssl = NULL;
684  port->ssl_in_use = false;
685  }
686 
687  if (port->peer)
688  {
689  X509_free(port->peer);
690  port->peer = NULL;
691  }
692 
693  if (port->peer_cn)
694  {
695  pfree(port->peer_cn);
696  port->peer_cn = NULL;
697  }
698 
699  if (port->peer_dn)
700  {
701  pfree(port->peer_dn);
702  port->peer_dn = NULL;
703  }
704 }
void pfree(void *pointer)
Definition: mcxt.c:1456
static int port
Definition: pg_regress.c:116

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_certificate_hash()

char* be_tls_get_certificate_hash ( Port port,
size_t *  len 
)

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

1436 {
1437  X509 *server_cert;
1438  char *cert_hash;
1439  const EVP_MD *algo_type = NULL;
1440  unsigned char hash[EVP_MAX_MD_SIZE]; /* size for SHA-512 */
1441  unsigned int hash_size;
1442  int algo_nid;
1443 
1444  *len = 0;
1445  server_cert = SSL_get_certificate(port->ssl);
1446  if (server_cert == NULL)
1447  return NULL;
1448 
1449  /*
1450  * Get the signature algorithm of the certificate to determine the hash
1451  * algorithm to use for the result. Prefer X509_get_signature_info(),
1452  * introduced in OpenSSL 1.1.1, which can handle RSA-PSS signatures.
1453  */
1454 #if HAVE_X509_GET_SIGNATURE_INFO
1455  if (!X509_get_signature_info(server_cert, &algo_nid, NULL, NULL, NULL))
1456 #else
1457  if (!OBJ_find_sigid_algs(X509_get_signature_nid(server_cert),
1458  &algo_nid, NULL))
1459 #endif
1460  elog(ERROR, "could not determine server certificate signature algorithm");
1461 
1462  /*
1463  * The TLS server's certificate bytes need to be hashed with SHA-256 if
1464  * its signature algorithm is MD5 or SHA-1 as per RFC 5929
1465  * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
1466  * is used, the same hash as the signature algorithm is used.
1467  */
1468  switch (algo_nid)
1469  {
1470  case NID_md5:
1471  case NID_sha1:
1472  algo_type = EVP_sha256();
1473  break;
1474  default:
1475  algo_type = EVP_get_digestbynid(algo_nid);
1476  if (algo_type == NULL)
1477  elog(ERROR, "could not find digest for NID %s",
1478  OBJ_nid2sn(algo_nid));
1479  break;
1480  }
1481 
1482  /* generate and save the certificate hash */
1483  if (!X509_digest(server_cert, algo_type, hash, &hash_size))
1484  elog(ERROR, "could not generate server certificate hash");
1485 
1486  cert_hash = palloc(hash_size);
1487  memcpy(cert_hash, hash, hash_size);
1488  *len = hash_size;
1489 
1490  return cert_hash;
1491 }
#define ERROR
Definition: elog.h:39
void * palloc(Size size)
Definition: mcxt.c:1226
const void size_t len
static unsigned hash(unsigned *uv, int n)
Definition: rege_dfa.c:715

References elog(), ERROR, hash(), len, palloc(), and port.

Referenced by read_client_final_message().

◆ be_tls_get_cipher()

const char* be_tls_get_cipher ( Port port)

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

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

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 1364 of file be-secure-openssl.c.

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

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 1405 of file be-secure-openssl.c.

1406 {
1407  if (port->peer)
1408  strlcpy(ptr, X509_NAME_to_cstring(X509_get_issuer_name(port->peer)), len);
1409  else
1410  ptr[0] = '\0';
1411 }
static char * X509_NAME_to_cstring(X509_NAME *name)
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 1414 of file be-secure-openssl.c.

1415 {
1416  if (port->peer)
1417  {
1418  ASN1_INTEGER *serial;
1419  BIGNUM *b;
1420  char *decimal;
1421 
1422  serial = X509_get_serialNumber(port->peer);
1423  b = ASN1_INTEGER_to_BN(serial, NULL);
1424  decimal = BN_bn2dec(b);
1425 
1426  BN_free(b);
1427  strlcpy(ptr, decimal, len);
1428  OPENSSL_free(decimal);
1429  }
1430  else
1431  ptr[0] = '\0';
1432 }
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 1396 of file be-secure-openssl.c.

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

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 1378 of file be-secure-openssl.c.

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

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:1202
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define LOG
Definition: elog.h:31
#define FATAL
Definition: elog.h:41
#define ereport(elevel,...)
Definition: elog.h:149
const char * GetConfigOption(const char *name, bool missing_ok, bool restrict_privileged)
Definition: guc.c:4229
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,
496  WAIT_EVENT_SSL_OPEN_SERVER);
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  if (port->peer_cn != NULL)
624  {
625  pfree(port->peer_cn);
626  port->peer_cn = NULL;
627  }
628  return -1;
629  }
630 
631  /*
632  * RFC2253 is the closest thing to an accepted standard format for
633  * DNs. We have documented how to produce this format from a
634  * certificate. It uses commas instead of slashes for delimiters,
635  * which make regular expression matching a bit easier. Also note that
636  * it prints the Subject fields in reverse order.
637  */
638  if (X509_NAME_print_ex(bio, x509name, 0, XN_FLAG_RFC2253) == -1 ||
639  BIO_get_mem_ptr(bio, &bio_buf) <= 0)
640  {
641  BIO_free(bio);
642  if (port->peer_cn != NULL)
643  {
644  pfree(port->peer_cn);
645  port->peer_cn = NULL;
646  }
647  return -1;
648  }
649  peer_dn = MemoryContextAlloc(TopMemoryContext, bio_buf->length + 1);
650  memcpy(peer_dn, bio_buf->data, bio_buf->length);
651  len = bio_buf->length;
652  BIO_free(bio);
653  peer_dn[len] = '\0';
654  if (len != strlen(peer_dn))
655  {
657  (errcode(ERRCODE_PROTOCOL_VIOLATION),
658  errmsg("SSL certificate's distinguished name contains embedded null")));
659  pfree(peer_dn);
660  if (port->peer_cn != NULL)
661  {
662  pfree(port->peer_cn);
663  port->peer_cn = NULL;
664  }
665  return -1;
666  }
667 
668  port->peer_dn = peer_dn;
669 
670  port->peer_cert_valid = true;
671  }
672 
673  return 0;
674 }
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:952
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1229
int errhint(const char *fmt,...)
Definition: elog.c:1316
#define COMMERROR
Definition: elog.h:33
void err(int eval, const char *fmt,...)
Definition: err.c:43
struct Latch * MyLatch
Definition: globals.c:58
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:566
#define WL_SOCKET_READABLE
Definition: latch.h:128
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:132
#define WL_SOCKET_WRITEABLE
Definition: latch.h:129
Assert(fmt[strlen(fmt) - 1] !='\n')
MemoryContext TopMemoryContext
Definition: mcxt.c:141
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1021

References Assert(), cert_errdetail, COMMERROR, ereport, err(), 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, 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 707 of file be-secure-openssl.c.

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

References COMMERROR, ECONNRESET, ereport, err(), 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 766 of file be-secure-openssl.c.

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

References COMMERROR, ECONNRESET, ereport, err(), 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 1627 of file be-secure-openssl.c.

1628 {
1629  if (isServerStart)
1630  {
1631  if (ssl_passphrase_command[0])
1632  SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
1633  }
1634  else
1635  {
1637  SSL_CTX_set_default_passwd_cb(context, ssl_external_passwd_cb);
1638  else
1639 
1640  /*
1641  * If reloading and no external command is configured, override
1642  * OpenSSL's default handling of passphrase-protected files,
1643  * because we don't want to prompt for a passphrase in an
1644  * already-running server.
1645  */
1646  SSL_CTX_set_default_passwd_cb(context, dummy_ssl_passwd_cb);
1647  }
1648 }
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 1076 of file be-secure-openssl.c.

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

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 1212 of file be-secure-openssl.c.

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

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

Referenced by be_tls_open_server().

◆ initialize_dh()

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

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

1270 {
1271  DH *dh = NULL;
1272 
1273  SSL_CTX_set_options(context, SSL_OP_SINGLE_DH_USE);
1274 
1275  if (ssl_dh_params_file[0])
1276  dh = load_dh_file(ssl_dh_params_file, isServerStart);
1277  if (!dh)
1278  dh = load_dh_buffer(FILE_DH2048, sizeof(FILE_DH2048));
1279  if (!dh)
1280  {
1281  ereport(isServerStart ? FATAL : LOG,
1282  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1283  errmsg("DH: could not load DH parameters")));
1284  return false;
1285  }
1286 
1287  if (SSL_CTX_set_tmp_dh(context, dh) != 1)
1288  {
1289  ereport(isServerStart ? FATAL : LOG,
1290  (errcode(ERRCODE_CONFIG_FILE_ERROR),
1291  errmsg("DH: could not set DH parameters: %s",
1292  SSLerrmessage(ERR_get_error()))));
1293  DH_free(dh);
1294  return false;
1295  }
1296 
1297  DH_free(dh);
1298  return true;
1299 }
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 1307 of file be-secure-openssl.c.

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

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

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 967 of file be-secure-openssl.c.

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

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 889 of file be-secure-openssl.c.

890 {
891  if (!my_bio_methods)
892  {
893  BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
894 #ifdef HAVE_BIO_METH_NEW
895  int my_bio_index;
896 
897  my_bio_index = BIO_get_new_index();
898  if (my_bio_index == -1)
899  return NULL;
900  my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
901  my_bio_methods = BIO_meth_new(my_bio_index, "PostgreSQL backend socket");
902  if (!my_bio_methods)
903  return NULL;
904  if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
905  !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
906  !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
907  !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
908  !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
909  !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
910  !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
911  !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
912  {
913  BIO_meth_free(my_bio_methods);
914  my_bio_methods = NULL;
915  return NULL;
916  }
917 #else
918  my_bio_methods = malloc(sizeof(BIO_METHOD));
919  if (!my_bio_methods)
920  return NULL;
921  memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
922  my_bio_methods->bread = my_sock_read;
923  my_bio_methods->bwrite = my_sock_write;
924 #endif
925  }
926  return my_bio_methods;
927 }
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 848 of file be-secure-openssl.c.

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

References 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 870 of file be-secure-openssl.c.

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

References 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 931 of file be-secure-openssl.c.

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

References err(), 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 1093 of file be-secure-openssl.c.

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

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 1056 of file be-secure-openssl.c.

1057 {
1058  /* same prompt as OpenSSL uses internally */
1059  const char *prompt = "Enter PEM pass phrase:";
1060 
1061  Assert(rwflag == 0);
1062 
1063  return run_ssl_passphrase_command(prompt, ssl_is_server_start, buf, size);
1064 }
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 1571 of file be-secure-openssl.c.

1572 {
1573  switch (v)
1574  {
1575  case PG_TLS_ANY:
1576  return 0;
1577  case PG_TLS1_VERSION:
1578  return TLS1_VERSION;
1579  case PG_TLS1_1_VERSION:
1580 #ifdef TLS1_1_VERSION
1581  return TLS1_1_VERSION;
1582 #else
1583  break;
1584 #endif
1585  case PG_TLS1_2_VERSION:
1586 #ifdef TLS1_2_VERSION
1587  return TLS1_2_VERSION;
1588 #else
1589  break;
1590 #endif
1591  case PG_TLS1_3_VERSION:
1592 #ifdef TLS1_3_VERSION
1593  return TLS1_3_VERSION;
1594 #else
1595  break;
1596 #endif
1597  }
1598 
1599  return -1;
1600 }
@ 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 1606 of file be-secure-openssl.c.

1607 {
1608  switch (v)
1609  {
1610  case PG_TLS_ANY:
1611  return "any";
1612  case PG_TLS1_VERSION:
1613  return "TLSv1";
1614  case PG_TLS1_1_VERSION:
1615  return "TLSv1.1";
1616  case PG_TLS1_2_VERSION:
1617  return "TLSv1.2";
1618  case PG_TLS1_3_VERSION:
1619  return "TLSv1.3";
1620  }
1621 
1622  return "(unrecognized)";
1623 }

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 1349 of file be-secure-openssl.c.

1350 {
1351  const char *errreason;
1352  static char errbuf[36];
1353 
1354  if (ecode == 0)
1355  return _("no SSL error reported");
1356  errreason = ERR_reason_error_string(ecode);
1357  if (errreason != NULL)
1358  return errreason;
1359  snprintf(errbuf, sizeof(errbuf), _("SSL error code %lu"), ecode);
1360  return errbuf;
1361 }
#define _(x)
Definition: elog.c:91
#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 1133 of file be-secure-openssl.c.

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

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