PostgreSQL Source Code  git master
fe-secure-openssl.c File Reference
#include "postgres_fe.h"
#include <signal.h>
#include <fcntl.h>
#include <ctype.h>
#include "libpq-fe.h"
#include "fe-auth.h"
#include "fe-secure-common.h"
#include "libpq-int.h"
#include "common/openssl.h"
#include <sys/socket.h>
#include <unistd.h>
#include <netdb.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <openssl/ssl.h>
#include <openssl/conf.h>
#include <openssl/x509v3.h>
Include dependency graph for fe-secure-openssl.c:

Go to the source code of this file.

Macros

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

Functions

static int verify_cb (int ok, X509_STORE_CTX *ctx)
 
static int openssl_verify_peer_name_matches_certificate_name (PGconn *conn, ASN1_STRING *name, char **store_name)
 
static void destroy_ssl_system (void)
 
static int initialize_SSL (PGconn *conn)
 
static PostgresPollingStatusType open_client_SSL (PGconn *)
 
static char * SSLerrmessage (unsigned long ecode)
 
static void SSLerrfree (char *buf)
 
static int PQssl_passwd_cb (char *buf, int size, int rwflag, void *userdata)
 
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 (PGconn *conn, int fd)
 
static int ssl_protocol_version_to_openssl (const char *protocol)
 
void pgtls_init_library (bool do_ssl, int do_crypto)
 
PostgresPollingStatusType pgtls_open_client (PGconn *conn)
 
ssize_t pgtls_read (PGconn *conn, void *ptr, size_t len)
 
bool pgtls_read_pending (PGconn *conn)
 
ssize_t pgtls_write (PGconn *conn, const void *ptr, size_t len)
 
int pgtls_verify_peer_name_matches_certificate_guts (PGconn *conn, int *names_examined, char **first_name)
 
int pgtls_init (PGconn *conn, bool do_ssl, bool do_crypto)
 
void pgtls_close (PGconn *conn)
 
void * PQgetssl (PGconn *conn)
 
void * PQsslStruct (PGconn *conn, const char *struct_name)
 
const char *const * PQsslAttributeNames (PGconn *conn)
 
const char * PQsslAttribute (PGconn *conn, const char *attribute_name)
 
int PQdefaultSSLKeyPassHook_OpenSSL (char *buf, int size, PGconn *conn)
 
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL (void)
 
void PQsetSSLKeyPassHook_OpenSSL (PQsslKeyPassHook_OpenSSL_type hook)
 

Variables

static bool pq_init_ssl_lib = true
 
static bool pq_init_crypto_lib = true
 
static bool ssl_lib_initialized = false
 
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook = NULL
 
static char ssl_nomem [] = "out of memory allocating error description"
 
static BIO_METHOD * my_bio_methods
 

Macro Definition Documentation

◆ BIO_get_data

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

Definition at line 1631 of file fe-secure-openssl.c.

Referenced by my_sock_read(), and my_sock_write().

◆ BIO_set_data

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

Definition at line 1632 of file fe-secure-openssl.c.

Referenced by my_SSL_set_fd().

◆ SSL_ERR_LEN

#define SSL_ERR_LEN   128

Definition at line 1513 of file fe-secure-openssl.c.

Referenced by SSLerrmessage().

Function Documentation

◆ destroy_ssl_system()

static void destroy_ssl_system ( void  )
static

Definition at line 747 of file fe-secure-openssl.c.

References pq_init_crypto_lib, pthread_mutex_lock(), and pthread_mutex_unlock().

Referenced by pgtls_close().

748 {
749 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
750  /* Mutex is created in pgtls_init() */
751  if (pthread_mutex_lock(&ssl_config_mutex))
752  return;
753 
754  if (pq_init_crypto_lib && crypto_open_connections > 0)
755  --crypto_open_connections;
756 
757  if (pq_init_crypto_lib && crypto_open_connections == 0)
758  {
759  /*
760  * No connections left, unregister libcrypto callbacks, if no one
761  * registered different ones in the meantime.
762  */
763  if (CRYPTO_get_locking_callback() == pq_lockingcallback)
764  CRYPTO_set_locking_callback(NULL);
765  if (CRYPTO_get_id_callback() == pq_threadidcallback)
766  CRYPTO_set_id_callback(NULL);
767 
768  /*
769  * We don't free the lock array. If we get another connection in this
770  * process, we will just re-use them with the existing mutexes.
771  *
772  * This means we leak a little memory on repeated load/unload of the
773  * library.
774  */
775  }
776 
777  pthread_mutex_unlock(&ssl_config_mutex);
778 #endif
779 }
int pthread_mutex_lock(pthread_mutex_t *mp)
Definition: pthread-win32.c:45
int pthread_mutex_unlock(pthread_mutex_t *mp)
Definition: pthread-win32.c:54
static bool pq_init_crypto_lib

◆ initialize_SSL()

static int initialize_SSL ( PGconn conn)
static

Definition at line 788 of file fe-secure-openssl.c.

References appendPQExpBuffer(), appendPQExpBufferStr(), pg_conn::connhost, pg_conn::errorMessage, free, pg_conn_host::host, libpq_gettext, MAXPGPATH, my_SSL_set_fd(), PG_STRERROR_R_BUFLEN, pqGetHomeDirectory(), PQssl_passwd_cb(), PQsslKeyPassHook, S_IRWXG, S_IRWXO, S_ISREG, snprintf, pg_conn::sock, SSL_context, SSL_CTX_set_max_proto_version(), SSL_CTX_set_min_proto_version(), pg_conn::ssl_in_use, pg_conn::ssl_max_protocol_version, pg_conn::ssl_min_protocol_version, ssl_protocol_version_to_openssl(), pg_conn::sslcert, pg_conn::sslcompression, pg_conn::sslcrl, pg_conn::sslcrldir, SSLerrfree(), SSLerrmessage(), pg_conn::sslkey, pg_conn::sslmode, pg_conn::sslpassword, pg_conn::sslrootcert, pg_conn::sslsni, stat::st_mode, stat, strerror_r, strlcpy(), verify_cb(), and pg_conn::whichhost.

Referenced by pgtls_open_client().

789 {
790  SSL_CTX *SSL_context;
791  struct stat buf;
792  char homedir[MAXPGPATH];
793  char fnbuf[MAXPGPATH];
794  char sebuf[PG_STRERROR_R_BUFLEN];
795  bool have_homedir;
796  bool have_cert;
797  bool have_rootcert;
798  EVP_PKEY *pkey = NULL;
799 
800  /*
801  * We'll need the home directory if any of the relevant parameters are
802  * defaulted. If pqGetHomeDirectory fails, act as though none of the
803  * files could be found.
804  */
805  if (!(conn->sslcert && strlen(conn->sslcert) > 0) ||
806  !(conn->sslkey && strlen(conn->sslkey) > 0) ||
807  !(conn->sslrootcert && strlen(conn->sslrootcert) > 0) ||
808  !((conn->sslcrl && strlen(conn->sslcrl) > 0) ||
809  (conn->sslcrldir && strlen(conn->sslcrldir) > 0)))
810  have_homedir = pqGetHomeDirectory(homedir, sizeof(homedir));
811  else /* won't need it */
812  have_homedir = false;
813 
814  /*
815  * Create a new SSL_CTX object.
816  *
817  * We used to share a single SSL_CTX between all connections, but it was
818  * complicated if connections used different certificates. So now we
819  * create a separate context for each connection, and accept the overhead.
820  */
821  SSL_context = SSL_CTX_new(SSLv23_method());
822  if (!SSL_context)
823  {
824  char *err = SSLerrmessage(ERR_get_error());
825 
827  libpq_gettext("could not create SSL context: %s\n"),
828  err);
829  SSLerrfree(err);
830  return -1;
831  }
832 
833  /*
834  * Delegate the client cert password prompt to the libpq wrapper callback
835  * if any is defined.
836  *
837  * If the application hasn't installed its own and the sslpassword
838  * parameter is non-null, we install ours now to make sure we supply
839  * PGconn->sslpassword to OpenSSL instead of letting it prompt on stdin.
840  *
841  * This will replace OpenSSL's default PEM_def_callback (which prompts on
842  * stdin), but we're only setting it for this SSL context so it's
843  * harmless.
844  */
845  if (PQsslKeyPassHook
846  || (conn->sslpassword && strlen(conn->sslpassword) > 0))
847  {
848  SSL_CTX_set_default_passwd_cb(SSL_context, PQssl_passwd_cb);
849  SSL_CTX_set_default_passwd_cb_userdata(SSL_context, conn);
850  }
851 
852  /* Disable old protocol versions */
853  SSL_CTX_set_options(SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
854 
855  /* Set the minimum and maximum protocol versions if necessary */
856  if (conn->ssl_min_protocol_version &&
857  strlen(conn->ssl_min_protocol_version) != 0)
858  {
859  int ssl_min_ver;
860 
862 
863  if (ssl_min_ver == -1)
864  {
866  libpq_gettext("invalid value \"%s\" for minimum SSL protocol version\n"),
868  SSL_CTX_free(SSL_context);
869  return -1;
870  }
871 
872  if (!SSL_CTX_set_min_proto_version(SSL_context, ssl_min_ver))
873  {
874  char *err = SSLerrmessage(ERR_get_error());
875 
877  libpq_gettext("could not set minimum SSL protocol version: %s\n"),
878  err);
879  SSLerrfree(err);
880  SSL_CTX_free(SSL_context);
881  return -1;
882  }
883  }
884 
885  if (conn->ssl_max_protocol_version &&
886  strlen(conn->ssl_max_protocol_version) != 0)
887  {
888  int ssl_max_ver;
889 
891 
892  if (ssl_max_ver == -1)
893  {
895  libpq_gettext("invalid value \"%s\" for maximum SSL protocol version\n"),
897  SSL_CTX_free(SSL_context);
898  return -1;
899  }
900 
901  if (!SSL_CTX_set_max_proto_version(SSL_context, ssl_max_ver))
902  {
903  char *err = SSLerrmessage(ERR_get_error());
904 
906  libpq_gettext("could not set maximum SSL protocol version: %s\n"),
907  err);
908  SSLerrfree(err);
909  SSL_CTX_free(SSL_context);
910  return -1;
911  }
912  }
913 
914  /*
915  * Disable OpenSSL's moving-write-buffer sanity check, because it causes
916  * unnecessary failures in nonblocking send cases.
917  */
918  SSL_CTX_set_mode(SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
919 
920  /*
921  * If the root cert file exists, load it so we can perform certificate
922  * verification. If sslmode is "verify-full" we will also do further
923  * verification after the connection has been completed.
924  */
925  if (conn->sslrootcert && strlen(conn->sslrootcert) > 0)
926  strlcpy(fnbuf, conn->sslrootcert, sizeof(fnbuf));
927  else if (have_homedir)
928  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CERT_FILE);
929  else
930  fnbuf[0] = '\0';
931 
932  if (fnbuf[0] != '\0' &&
933  stat(fnbuf, &buf) == 0)
934  {
935  X509_STORE *cvstore;
936 
937  if (SSL_CTX_load_verify_locations(SSL_context, fnbuf, NULL) != 1)
938  {
939  char *err = SSLerrmessage(ERR_get_error());
940 
942  libpq_gettext("could not read root certificate file \"%s\": %s\n"),
943  fnbuf, err);
944  SSLerrfree(err);
945  SSL_CTX_free(SSL_context);
946  return -1;
947  }
948 
949  if ((cvstore = SSL_CTX_get_cert_store(SSL_context)) != NULL)
950  {
951  char *fname = NULL;
952  char *dname = NULL;
953 
954  if (conn->sslcrl && strlen(conn->sslcrl) > 0)
955  fname = conn->sslcrl;
956  if (conn->sslcrldir && strlen(conn->sslcrldir) > 0)
957  dname = conn->sslcrldir;
958 
959  /* defaults to use the default CRL file */
960  if (!fname && !dname && have_homedir)
961  {
962  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, ROOT_CRL_FILE);
963  fname = fnbuf;
964  }
965 
966  /* Set the flags to check against the complete CRL chain */
967  if ((fname || dname) &&
968  X509_STORE_load_locations(cvstore, fname, dname) == 1)
969  {
970  X509_STORE_set_flags(cvstore,
971  X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
972  }
973 
974  /* if not found, silently ignore; we do not require CRL */
975  ERR_clear_error();
976  }
977  have_rootcert = true;
978  }
979  else
980  {
981  /*
982  * stat() failed; assume root file doesn't exist. If sslmode is
983  * verify-ca or verify-full, this is an error. Otherwise, continue
984  * without performing any server cert verification.
985  */
986  if (conn->sslmode[0] == 'v') /* "verify-ca" or "verify-full" */
987  {
988  /*
989  * The only way to reach here with an empty filename is if
990  * pqGetHomeDirectory failed. That's a sufficiently unusual case
991  * that it seems worth having a specialized error message for it.
992  */
993  if (fnbuf[0] == '\0')
995  libpq_gettext("could not get home directory to locate root certificate file\n"
996  "Either provide the file or change sslmode to disable server certificate verification.\n"));
997  else
999  libpq_gettext("root certificate file \"%s\" does not exist\n"
1000  "Either provide the file or change sslmode to disable server certificate verification.\n"), fnbuf);
1001  SSL_CTX_free(SSL_context);
1002  return -1;
1003  }
1004  have_rootcert = false;
1005  }
1006 
1007  /* Read the client certificate file */
1008  if (conn->sslcert && strlen(conn->sslcert) > 0)
1009  strlcpy(fnbuf, conn->sslcert, sizeof(fnbuf));
1010  else if (have_homedir)
1011  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_CERT_FILE);
1012  else
1013  fnbuf[0] = '\0';
1014 
1015  if (fnbuf[0] == '\0')
1016  {
1017  /* no home directory, proceed without a client cert */
1018  have_cert = false;
1019  }
1020  else if (stat(fnbuf, &buf) != 0)
1021  {
1022  /*
1023  * If file is not present, just go on without a client cert; server
1024  * might or might not accept the connection. Any other error,
1025  * however, is grounds for complaint.
1026  */
1027  if (errno != ENOENT && errno != ENOTDIR)
1028  {
1030  libpq_gettext("could not open certificate file \"%s\": %s\n"),
1031  fnbuf, strerror_r(errno, sebuf, sizeof(sebuf)));
1032  SSL_CTX_free(SSL_context);
1033  return -1;
1034  }
1035  have_cert = false;
1036  }
1037  else
1038  {
1039  /*
1040  * Cert file exists, so load it. Since OpenSSL doesn't provide the
1041  * equivalent of "SSL_use_certificate_chain_file", we have to load it
1042  * into the SSL context, rather than the SSL object.
1043  */
1044  if (SSL_CTX_use_certificate_chain_file(SSL_context, fnbuf) != 1)
1045  {
1046  char *err = SSLerrmessage(ERR_get_error());
1047 
1049  libpq_gettext("could not read certificate file \"%s\": %s\n"),
1050  fnbuf, err);
1051  SSLerrfree(err);
1052  SSL_CTX_free(SSL_context);
1053  return -1;
1054  }
1055 
1056  /* need to load the associated private key, too */
1057  have_cert = true;
1058  }
1059 
1060  /*
1061  * The SSL context is now loaded with the correct root and client
1062  * certificates. Create a connection-specific SSL object. The private key
1063  * is loaded directly into the SSL object. (We could load the private key
1064  * into the context, too, but we have done it this way historically, and
1065  * it doesn't really matter.)
1066  */
1067  if (!(conn->ssl = SSL_new(SSL_context)) ||
1068  !SSL_set_app_data(conn->ssl, conn) ||
1069  !my_SSL_set_fd(conn, conn->sock))
1070  {
1071  char *err = SSLerrmessage(ERR_get_error());
1072 
1074  libpq_gettext("could not establish SSL connection: %s\n"),
1075  err);
1076  SSLerrfree(err);
1077  SSL_CTX_free(SSL_context);
1078  return -1;
1079  }
1080  conn->ssl_in_use = true;
1081 
1082  /*
1083  * SSL contexts are reference counted by OpenSSL. We can free it as soon
1084  * as we have created the SSL object, and it will stick around for as long
1085  * as it's actually needed.
1086  */
1087  SSL_CTX_free(SSL_context);
1088  SSL_context = NULL;
1089 
1090  /*
1091  * Set Server Name Indication (SNI), if enabled by connection parameters.
1092  * Per RFC 6066, do not set it if the host is a literal IP address (IPv4
1093  * or IPv6).
1094  */
1095  if (conn->sslsni && conn->sslsni[0] == '1')
1096  {
1097  const char *host = conn->connhost[conn->whichhost].host;
1098 
1099  if (host && host[0] &&
1100  !(strspn(host, "0123456789.") == strlen(host) ||
1101  strchr(host, ':')))
1102  {
1103  if (SSL_set_tlsext_host_name(conn->ssl, host) != 1)
1104  {
1105  char *err = SSLerrmessage(ERR_get_error());
1106 
1108  libpq_gettext("could not set SSL Server Name Indication (SNI): %s\n"),
1109  err);
1110  SSLerrfree(err);
1111  return -1;
1112  }
1113  }
1114  }
1115 
1116  /*
1117  * Read the SSL key. If a key is specified, treat it as an engine:key
1118  * combination if there is colon present - we don't support files with
1119  * colon in the name. The exception is if the second character is a colon,
1120  * in which case it can be a Windows filename with drive specification.
1121  */
1122  if (have_cert && conn->sslkey && strlen(conn->sslkey) > 0)
1123  {
1124 #ifdef USE_SSL_ENGINE
1125  if (strchr(conn->sslkey, ':')
1126 #ifdef WIN32
1127  && conn->sslkey[1] != ':'
1128 #endif
1129  )
1130  {
1131  /* Colon, but not in second character, treat as engine:key */
1132  char *engine_str = strdup(conn->sslkey);
1133  char *engine_colon;
1134 
1135  if (engine_str == NULL)
1136  {
1138  libpq_gettext("out of memory\n"));
1139  return -1;
1140  }
1141 
1142  /* cannot return NULL because we already checked before strdup */
1143  engine_colon = strchr(engine_str, ':');
1144 
1145  *engine_colon = '\0'; /* engine_str now has engine name */
1146  engine_colon++; /* engine_colon now has key name */
1147 
1148  conn->engine = ENGINE_by_id(engine_str);
1149  if (conn->engine == NULL)
1150  {
1151  char *err = SSLerrmessage(ERR_get_error());
1152 
1154  libpq_gettext("could not load SSL engine \"%s\": %s\n"),
1155  engine_str, err);
1156  SSLerrfree(err);
1157  free(engine_str);
1158  return -1;
1159  }
1160 
1161  if (ENGINE_init(conn->engine) == 0)
1162  {
1163  char *err = SSLerrmessage(ERR_get_error());
1164 
1166  libpq_gettext("could not initialize SSL engine \"%s\": %s\n"),
1167  engine_str, err);
1168  SSLerrfree(err);
1169  ENGINE_free(conn->engine);
1170  conn->engine = NULL;
1171  free(engine_str);
1172  return -1;
1173  }
1174 
1175  pkey = ENGINE_load_private_key(conn->engine, engine_colon,
1176  NULL, NULL);
1177  if (pkey == NULL)
1178  {
1179  char *err = SSLerrmessage(ERR_get_error());
1180 
1182  libpq_gettext("could not read private SSL key \"%s\" from engine \"%s\": %s\n"),
1183  engine_colon, engine_str, err);
1184  SSLerrfree(err);
1185  ENGINE_finish(conn->engine);
1186  ENGINE_free(conn->engine);
1187  conn->engine = NULL;
1188  free(engine_str);
1189  return -1;
1190  }
1191  if (SSL_use_PrivateKey(conn->ssl, pkey) != 1)
1192  {
1193  char *err = SSLerrmessage(ERR_get_error());
1194 
1196  libpq_gettext("could not load private SSL key \"%s\" from engine \"%s\": %s\n"),
1197  engine_colon, engine_str, err);
1198  SSLerrfree(err);
1199  ENGINE_finish(conn->engine);
1200  ENGINE_free(conn->engine);
1201  conn->engine = NULL;
1202  free(engine_str);
1203  return -1;
1204  }
1205 
1206  free(engine_str);
1207 
1208  fnbuf[0] = '\0'; /* indicate we're not going to load from a
1209  * file */
1210  }
1211  else
1212 #endif /* USE_SSL_ENGINE */
1213  {
1214  /* PGSSLKEY is not an engine, treat it as a filename */
1215  strlcpy(fnbuf, conn->sslkey, sizeof(fnbuf));
1216  }
1217  }
1218  else if (have_homedir)
1219  {
1220  /* No PGSSLKEY specified, load default file */
1221  snprintf(fnbuf, sizeof(fnbuf), "%s/%s", homedir, USER_KEY_FILE);
1222  }
1223  else
1224  fnbuf[0] = '\0';
1225 
1226  if (have_cert && fnbuf[0] != '\0')
1227  {
1228  /* read the client key from file */
1229 
1230  if (stat(fnbuf, &buf) != 0)
1231  {
1233  libpq_gettext("certificate present, but not private key file \"%s\"\n"),
1234  fnbuf);
1235  return -1;
1236  }
1237 #ifndef WIN32
1238  if (!S_ISREG(buf.st_mode) || buf.st_mode & (S_IRWXG | S_IRWXO))
1239  {
1241  libpq_gettext("private key file \"%s\" has group or world access; permissions should be u=rw (0600) or less\n"),
1242  fnbuf);
1243  return -1;
1244  }
1245 #endif
1246 
1247  if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1248  {
1249  char *err = SSLerrmessage(ERR_get_error());
1250 
1251  /*
1252  * We'll try to load the file in DER (binary ASN.1) format, and if
1253  * that fails too, report the original error. This could mask
1254  * issues where there's something wrong with a DER-format cert,
1255  * but we'd have to duplicate openssl's format detection to be
1256  * smarter than this. We can't just probe for a leading -----BEGIN
1257  * because PEM can have leading non-matching lines and blanks.
1258  * OpenSSL doesn't expose its get_name(...) and its PEM routines
1259  * don't differentiate between failure modes in enough detail to
1260  * let us tell the difference between "not PEM, try DER" and
1261  * "wrong password".
1262  */
1263  if (SSL_use_PrivateKey_file(conn->ssl, fnbuf, SSL_FILETYPE_ASN1) != 1)
1264  {
1266  libpq_gettext("could not load private key file \"%s\": %s\n"),
1267  fnbuf, err);
1268  SSLerrfree(err);
1269  return -1;
1270  }
1271 
1272  SSLerrfree(err);
1273 
1274  }
1275  }
1276 
1277  /* verify that the cert and key go together */
1278  if (have_cert &&
1279  SSL_check_private_key(conn->ssl) != 1)
1280  {
1281  char *err = SSLerrmessage(ERR_get_error());
1282 
1284  libpq_gettext("certificate does not match private key file \"%s\": %s\n"),
1285  fnbuf, err);
1286  SSLerrfree(err);
1287  return -1;
1288  }
1289 
1290  /*
1291  * If a root cert was loaded, also set our certificate verification
1292  * callback.
1293  */
1294  if (have_rootcert)
1295  SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, verify_cb);
1296 
1297  /*
1298  * Set compression option if necessary.
1299  */
1300  if (conn->sslcompression && conn->sslcompression[0] == '0')
1301  SSL_set_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1302  else
1303  SSL_clear_options(conn->ssl, SSL_OP_NO_COMPRESSION);
1304 
1305  return 0;
1306 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define PG_STRERROR_R_BUFLEN
Definition: port.h:235
char * host
Definition: libpq-int.h:335
char * sslsni
Definition: libpq-int.h:387
char * ssl_min_protocol_version
Definition: libpq-int.h:393
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook
static int PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
char * sslkey
Definition: libpq-int.h:381
char * sslcompression
Definition: libpq-int.h:380
#define MAXPGPATH
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
pg_conn_host * connhost
Definition: libpq-int.h:427
bool ssl_in_use
Definition: libpq-int.h:508
static char * buf
Definition: pg_test_fsync.c:68
#define S_IRWXG
Definition: win32_port.h:309
char * sslpassword
Definition: libpq-int.h:383
static int verify_cb(int ok, X509_STORE_CTX *ctx)
pgsocket sock
Definition: libpq-int.h:444
#define S_ISREG(m)
Definition: win32_port.h:327
static int my_SSL_set_fd(PGconn *conn, int fd)
static void SSLerrfree(char *buf)
char * sslmode
Definition: libpq-int.h:379
PQExpBufferData errorMessage
Definition: libpq-int.h:571
char * sslcert
Definition: libpq-int.h:382
#define free(a)
Definition: header.h:65
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
int SSL_CTX_set_min_proto_version(SSL_CTX *ctx, int version)
static int ssl_protocol_version_to_openssl(const char *protocol)
#define strerror_r
Definition: port.h:234
char * sslrootcert
Definition: libpq-int.h:384
static char * SSLerrmessage(unsigned long ecode)
static SSL_CTX * SSL_context
char * ssl_max_protocol_version
Definition: libpq-int.h:394
bool pqGetHomeDirectory(char *buf, int bufsize)
Definition: fe-connect.c:7242
char * sslcrldir
Definition: libpq-int.h:386
int SSL_CTX_set_max_proto_version(SSL_CTX *ctx, int version)
#define snprintf
Definition: port.h:217
char * sslcrl
Definition: libpq-int.h:385
#define S_IRWXO
Definition: win32_port.h:321
int whichhost
Definition: libpq-int.h:426
#define libpq_gettext(x)
Definition: libpq-int.h:841
#define stat
Definition: win32_port.h:283

◆ my_BIO_s_socket()

static BIO_METHOD * my_BIO_s_socket ( void  )
static

Definition at line 1698 of file fe-secure-openssl.c.

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

Referenced by my_SSL_set_fd().

1699 {
1700  if (!my_bio_methods)
1701  {
1702  BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1703 #ifdef HAVE_BIO_METH_NEW
1704  int my_bio_index;
1705 
1706  my_bio_index = BIO_get_new_index();
1707  if (my_bio_index == -1)
1708  return NULL;
1709  my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
1710  my_bio_methods = BIO_meth_new(my_bio_index, "libpq socket");
1711  if (!my_bio_methods)
1712  return NULL;
1713 
1714  /*
1715  * As of this writing, these functions never fail. But check anyway,
1716  * like OpenSSL's own examples do.
1717  */
1718  if (!BIO_meth_set_write(my_bio_methods, my_sock_write) ||
1719  !BIO_meth_set_read(my_bio_methods, my_sock_read) ||
1720  !BIO_meth_set_gets(my_bio_methods, BIO_meth_get_gets(biom)) ||
1721  !BIO_meth_set_puts(my_bio_methods, BIO_meth_get_puts(biom)) ||
1722  !BIO_meth_set_ctrl(my_bio_methods, BIO_meth_get_ctrl(biom)) ||
1723  !BIO_meth_set_create(my_bio_methods, BIO_meth_get_create(biom)) ||
1724  !BIO_meth_set_destroy(my_bio_methods, BIO_meth_get_destroy(biom)) ||
1725  !BIO_meth_set_callback_ctrl(my_bio_methods, BIO_meth_get_callback_ctrl(biom)))
1726  {
1727  BIO_meth_free(my_bio_methods);
1728  my_bio_methods = NULL;
1729  return NULL;
1730  }
1731 #else
1732  my_bio_methods = malloc(sizeof(BIO_METHOD));
1733  if (!my_bio_methods)
1734  return NULL;
1735  memcpy(my_bio_methods, biom, sizeof(BIO_METHOD));
1736  my_bio_methods->bread = my_sock_read;
1737  my_bio_methods->bwrite = my_sock_write;
1738 #endif
1739  }
1740  return my_bio_methods;
1741 }
static int my_sock_write(BIO *h, const char *buf, int size)
#define malloc(a)
Definition: header.h:50
static BIO_METHOD * my_bio_methods
static int my_sock_read(BIO *h, char *buf, int size)

◆ my_sock_read()

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

Definition at line 1638 of file fe-secure-openssl.c.

References BIO_get_data, EAGAIN, EINTR, EWOULDBLOCK, pqsecure_raw_read(), and SOCK_ERRNO.

Referenced by my_BIO_s_socket().

1639 {
1640  int res;
1641 
1642  res = pqsecure_raw_read((PGconn *) BIO_get_data(h), buf, size);
1643  BIO_clear_retry_flags(h);
1644  if (res < 0)
1645  {
1646  /* If we were interrupted, tell caller to retry */
1647  switch (SOCK_ERRNO)
1648  {
1649 #ifdef EAGAIN
1650  case EAGAIN:
1651 #endif
1652 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1653  case EWOULDBLOCK:
1654 #endif
1655  case EINTR:
1656  BIO_set_retry_read(h);
1657  break;
1658 
1659  default:
1660  break;
1661  }
1662  }
1663 
1664  return res;
1665 }
#define EAGAIN
Definition: win32_port.h:349
ssize_t pqsecure_raw_read(PGconn *conn, void *ptr, size_t len)
Definition: fe-secure.c:232
#define SOCK_ERRNO
Definition: libpq-int.h:854
static char * buf
Definition: pg_test_fsync.c:68
#define EWOULDBLOCK
Definition: win32_port.h:357
#define EINTR
Definition: win32_port.h:351
#define BIO_get_data(bio)

◆ my_sock_write()

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

Definition at line 1668 of file fe-secure-openssl.c.

References BIO_get_data, EAGAIN, EINTR, EWOULDBLOCK, pqsecure_raw_write(), and SOCK_ERRNO.

Referenced by my_BIO_s_socket().

1669 {
1670  int res;
1671 
1672  res = pqsecure_raw_write((PGconn *) BIO_get_data(h), buf, size);
1673  BIO_clear_retry_flags(h);
1674  if (res <= 0)
1675  {
1676  /* If we were interrupted, tell caller to retry */
1677  switch (SOCK_ERRNO)
1678  {
1679 #ifdef EAGAIN
1680  case EAGAIN:
1681 #endif
1682 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1683  case EWOULDBLOCK:
1684 #endif
1685  case EINTR:
1686  BIO_set_retry_write(h);
1687  break;
1688 
1689  default:
1690  break;
1691  }
1692  }
1693 
1694  return res;
1695 }
#define EAGAIN
Definition: win32_port.h:349
#define SOCK_ERRNO
Definition: libpq-int.h:854
static char * buf
Definition: pg_test_fsync.c:68
ssize_t pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
Definition: fe-secure.c:314
#define EWOULDBLOCK
Definition: win32_port.h:357
#define EINTR
Definition: win32_port.h:351
#define BIO_get_data(bio)

◆ my_SSL_set_fd()

static int my_SSL_set_fd ( PGconn conn,
int  fd 
)
static

Definition at line 1745 of file fe-secure-openssl.c.

References BIO_set_data, and my_BIO_s_socket().

Referenced by initialize_SSL().

1746 {
1747  int ret = 0;
1748  BIO *bio;
1749  BIO_METHOD *bio_method;
1750 
1751  bio_method = my_BIO_s_socket();
1752  if (bio_method == NULL)
1753  {
1754  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1755  goto err;
1756  }
1757  bio = BIO_new(bio_method);
1758  if (bio == NULL)
1759  {
1760  SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1761  goto err;
1762  }
1763  BIO_set_data(bio, conn);
1764 
1765  SSL_set_bio(conn->ssl, bio, bio);
1766  BIO_set_fd(bio, fd, BIO_NOCLOSE);
1767  ret = 1;
1768 err:
1769  return ret;
1770 }
#define BIO_set_data(bio, data)
static int fd(const char *x, int i)
Definition: preproc-init.c:105
static BIO_METHOD * my_BIO_s_socket(void)

◆ open_client_SSL()

static PostgresPollingStatusType open_client_SSL ( PGconn conn)
static

Definition at line 1312 of file fe-secure-openssl.c.

References appendPQExpBuffer(), appendPQExpBufferStr(), pg_conn::errorMessage, libpq_gettext, PG_STRERROR_R_BUFLEN, PGRES_POLLING_FAILED, PGRES_POLLING_OK, PGRES_POLLING_READING, PGRES_POLLING_WRITING, pgtls_close(), pq_verify_peer_name_matches_certificate(), SOCK_ERRNO, SOCK_STRERROR, pg_conn::ssl_max_protocol_version, pg_conn::ssl_min_protocol_version, SSLerrfree(), and SSLerrmessage().

Referenced by pgtls_open_client().

1313 {
1314  int r;
1315 
1316  ERR_clear_error();
1317  r = SSL_connect(conn->ssl);
1318  if (r <= 0)
1319  {
1320  int err = SSL_get_error(conn->ssl, r);
1321  unsigned long ecode;
1322 
1323  ecode = ERR_get_error();
1324  switch (err)
1325  {
1326  case SSL_ERROR_WANT_READ:
1327  return PGRES_POLLING_READING;
1328 
1329  case SSL_ERROR_WANT_WRITE:
1330  return PGRES_POLLING_WRITING;
1331 
1332  case SSL_ERROR_SYSCALL:
1333  {
1334  char sebuf[PG_STRERROR_R_BUFLEN];
1335 
1336  if (r == -1)
1338  libpq_gettext("SSL SYSCALL error: %s\n"),
1339  SOCK_STRERROR(SOCK_ERRNO, sebuf, sizeof(sebuf)));
1340  else
1342  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
1343  pgtls_close(conn);
1344  return PGRES_POLLING_FAILED;
1345  }
1346  case SSL_ERROR_SSL:
1347  {
1348  char *err = SSLerrmessage(ecode);
1349 
1351  libpq_gettext("SSL error: %s\n"),
1352  err);
1353  SSLerrfree(err);
1354  switch (ERR_GET_REASON(ecode))
1355  {
1356  /*
1357  * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
1358  * TLSV1_ALERT_PROTOCOL_VERSION have been observed
1359  * when trying to communicate with an old OpenSSL
1360  * library, or when the client and server specify
1361  * disjoint protocol ranges.
1362  * NO_PROTOCOLS_AVAILABLE occurs if there's a
1363  * local misconfiguration (which can happen
1364  * despite our checks, if openssl.cnf injects a
1365  * limit we didn't account for). It's not very
1366  * clear what would make OpenSSL return the other
1367  * codes listed here, but a hint about protocol
1368  * versions seems like it's appropriate for all.
1369  */
1370  case SSL_R_NO_PROTOCOLS_AVAILABLE:
1371  case SSL_R_UNSUPPORTED_PROTOCOL:
1372  case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
1373  case SSL_R_UNKNOWN_PROTOCOL:
1374  case SSL_R_UNKNOWN_SSL_VERSION:
1375  case SSL_R_UNSUPPORTED_SSL_VERSION:
1376  case SSL_R_WRONG_SSL_VERSION:
1377  case SSL_R_WRONG_VERSION_NUMBER:
1378  case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
1379 #ifdef SSL_R_VERSION_TOO_HIGH
1380  case SSL_R_VERSION_TOO_HIGH:
1381  case SSL_R_VERSION_TOO_LOW:
1382 #endif
1384  libpq_gettext("This may indicate that the server does not support any SSL protocol version between %s and %s.\n"),
1385  conn->ssl_min_protocol_version ?
1386  conn->ssl_min_protocol_version :
1387  MIN_OPENSSL_TLS_VERSION,
1388  conn->ssl_max_protocol_version ?
1389  conn->ssl_max_protocol_version :
1390  MAX_OPENSSL_TLS_VERSION);
1391  break;
1392  default:
1393  break;
1394  }
1395  pgtls_close(conn);
1396  return PGRES_POLLING_FAILED;
1397  }
1398 
1399  default:
1401  libpq_gettext("unrecognized SSL error code: %d\n"),
1402  err);
1403  pgtls_close(conn);
1404  return PGRES_POLLING_FAILED;
1405  }
1406  }
1407 
1408  /*
1409  * We already checked the server certificate in initialize_SSL() using
1410  * SSL_CTX_set_verify(), if root.crt exists.
1411  */
1412 
1413  /* get server certificate */
1414  conn->peer = SSL_get_peer_certificate(conn->ssl);
1415  if (conn->peer == NULL)
1416  {
1417  char *err = SSLerrmessage(ERR_get_error());
1418 
1420  libpq_gettext("certificate could not be obtained: %s\n"),
1421  err);
1422  SSLerrfree(err);
1423  pgtls_close(conn);
1424  return PGRES_POLLING_FAILED;
1425  }
1426 
1428  {
1429  pgtls_close(conn);
1430  return PGRES_POLLING_FAILED;
1431  }
1432 
1433  /* SSL handshake is complete */
1434  return PGRES_POLLING_OK;
1435 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define PG_STRERROR_R_BUFLEN
Definition: port.h:235
char * ssl_min_protocol_version
Definition: libpq-int.h:393
#define SOCK_STRERROR
Definition: libpq-int.h:855
#define SOCK_ERRNO
Definition: libpq-int.h:854
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
bool pq_verify_peer_name_matches_certificate(PGconn *conn)
static void SSLerrfree(char *buf)
void pgtls_close(PGconn *conn)
PQExpBufferData errorMessage
Definition: libpq-int.h:571
static char * SSLerrmessage(unsigned long ecode)
char * ssl_max_protocol_version
Definition: libpq-int.h:394
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ openssl_verify_peer_name_matches_certificate_name()

static int openssl_verify_peer_name_matches_certificate_name ( PGconn conn,
ASN1_STRING *  name,
char **  store_name 
)
static

Definition at line 478 of file fe-secure-openssl.c.

References appendPQExpBufferStr(), pg_conn::errorMessage, libpq_gettext, and pq_verify_peer_name_matches_certificate_name().

Referenced by pgtls_verify_peer_name_matches_certificate_guts().

480 {
481  int len;
482  const unsigned char *namedata;
483 
484  /* Should not happen... */
485  if (name_entry == NULL)
486  {
488  libpq_gettext("SSL certificate's name entry is missing\n"));
489  return -1;
490  }
491 
492  /*
493  * GEN_DNS can be only IA5String, equivalent to US ASCII.
494  */
495 #ifdef HAVE_ASN1_STRING_GET0_DATA
496  namedata = ASN1_STRING_get0_data(name_entry);
497 #else
498  namedata = ASN1_STRING_data(name_entry);
499 #endif
500  len = ASN1_STRING_length(name_entry);
501 
502  /* OK to cast from unsigned to plain char, since it's all ASCII. */
503  return pq_verify_peer_name_matches_certificate_name(conn, (const char *) namedata, len, store_name);
504 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
int pq_verify_peer_name_matches_certificate_name(PGconn *conn, const char *namedata, size_t namelen, char **store_name)
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ pgtls_close()

void pgtls_close ( PGconn conn)

Definition at line 1438 of file fe-secure-openssl.c.

References destroy_ssl_system(), and pg_conn::ssl_in_use.

Referenced by open_client_SSL(), pgtls_open_client(), and pqsecure_close().

1439 {
1440  bool destroy_needed = false;
1441 
1442  if (conn->ssl_in_use)
1443  {
1444  if (conn->ssl)
1445  {
1446  /*
1447  * We can't destroy everything SSL-related here due to the
1448  * possible later calls to OpenSSL routines which may need our
1449  * thread callbacks, so set a flag here and check at the end.
1450  */
1451 
1452  SSL_shutdown(conn->ssl);
1453  SSL_free(conn->ssl);
1454  conn->ssl = NULL;
1455  conn->ssl_in_use = false;
1456 
1457  destroy_needed = true;
1458  }
1459 
1460  if (conn->peer)
1461  {
1462  X509_free(conn->peer);
1463  conn->peer = NULL;
1464  }
1465 
1466 #ifdef USE_SSL_ENGINE
1467  if (conn->engine)
1468  {
1469  ENGINE_finish(conn->engine);
1470  ENGINE_free(conn->engine);
1471  conn->engine = NULL;
1472  }
1473 #endif
1474  }
1475  else
1476  {
1477  /*
1478  * In the non-SSL case, just remove the crypto callbacks if the
1479  * connection has then loaded. This code path has no dependency on
1480  * any pending SSL calls.
1481  */
1482  if (conn->crypto_loaded)
1483  destroy_needed = true;
1484  }
1485 
1486  /*
1487  * This will remove our crypto locking hooks if this is the last
1488  * connection using libcrypto which means we must wait to call it until
1489  * after all the potential SSL calls have been made, otherwise we can end
1490  * up with a race condition and possible deadlocks.
1491  *
1492  * See comments above destroy_ssl_system().
1493  */
1494  if (destroy_needed)
1495  {
1497  conn->crypto_loaded = false;
1498  }
1499 }
bool ssl_in_use
Definition: libpq-int.h:508
static void destroy_ssl_system(void)

◆ pgtls_init()

int pgtls_init ( PGconn conn,
bool  do_ssl,
bool  do_crypto 
)

Definition at line 643 of file fe-secure-openssl.c.

References free, i, malloc, pq_init_crypto_lib, pq_init_ssl_lib, pthread_mutex_init(), pthread_mutex_lock(), pthread_mutex_unlock(), and ssl_lib_initialized.

Referenced by pqsecure_initialize().

644 {
645 #ifdef ENABLE_THREAD_SAFETY
646 #ifdef WIN32
647  /* Also see similar code in fe-connect.c, default_threadlock() */
648  if (ssl_config_mutex == NULL)
649  {
650  while (InterlockedExchange(&win32_ssl_create_mutex, 1) == 1)
651  /* loop, another thread own the lock */ ;
652  if (ssl_config_mutex == NULL)
653  {
654  if (pthread_mutex_init(&ssl_config_mutex, NULL))
655  return -1;
656  }
657  InterlockedExchange(&win32_ssl_create_mutex, 0);
658  }
659 #endif
660  if (pthread_mutex_lock(&ssl_config_mutex))
661  return -1;
662 
663 #ifdef HAVE_CRYPTO_LOCK
664  if (pq_init_crypto_lib)
665  {
666  /*
667  * If necessary, set up an array to hold locks for libcrypto.
668  * libcrypto will tell us how big to make this array.
669  */
670  if (pq_lockarray == NULL)
671  {
672  int i;
673 
674  pq_lockarray = malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
675  if (!pq_lockarray)
676  {
677  pthread_mutex_unlock(&ssl_config_mutex);
678  return -1;
679  }
680  for (i = 0; i < CRYPTO_num_locks(); i++)
681  {
682  if (pthread_mutex_init(&pq_lockarray[i], NULL))
683  {
684  free(pq_lockarray);
685  pq_lockarray = NULL;
686  pthread_mutex_unlock(&ssl_config_mutex);
687  return -1;
688  }
689  }
690  }
691 
692  if (do_crypto && !conn->crypto_loaded)
693  {
694  if (crypto_open_connections++ == 0)
695  {
696  /*
697  * These are only required for threaded libcrypto
698  * applications, but make sure we don't stomp on them if
699  * they're already set.
700  */
701  if (CRYPTO_get_id_callback() == NULL)
702  CRYPTO_set_id_callback(pq_threadidcallback);
703  if (CRYPTO_get_locking_callback() == NULL)
704  CRYPTO_set_locking_callback(pq_lockingcallback);
705  }
706 
707  conn->crypto_loaded = true;
708  }
709  }
710 #endif /* HAVE_CRYPTO_LOCK */
711 #endif /* ENABLE_THREAD_SAFETY */
712 
713  if (!ssl_lib_initialized && do_ssl)
714  {
715  if (pq_init_ssl_lib)
716  {
717 #ifdef HAVE_OPENSSL_INIT_SSL
718  OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG, NULL);
719 #else
720  OPENSSL_config(NULL);
721  SSL_library_init();
722  SSL_load_error_strings();
723 #endif
724  }
725  ssl_lib_initialized = true;
726  }
727 
728 #ifdef ENABLE_THREAD_SAFETY
729  pthread_mutex_unlock(&ssl_config_mutex);
730 #endif
731  return 0;
732 }
static bool pq_init_ssl_lib
CRITICAL_SECTION * pthread_mutex_t
Definition: pthread-win32.h:8
int pthread_mutex_init(pthread_mutex_t *mp, void *attr)
Definition: pthread-win32.c:35
#define malloc(a)
Definition: header.h:50
int pthread_mutex_lock(pthread_mutex_t *mp)
Definition: pthread-win32.c:45
int pthread_mutex_unlock(pthread_mutex_t *mp)
Definition: pthread-win32.c:54
static bool pq_init_crypto_lib
#define free(a)
Definition: header.h:65
int i
static bool ssl_lib_initialized

◆ pgtls_init_library()

void pgtls_init_library ( bool  do_ssl,
int  do_crypto 
)

Definition at line 106 of file fe-secure-openssl.c.

References pq_init_crypto_lib, and pq_init_ssl_lib.

Referenced by PQinitOpenSSL(), and PQinitSSL().

107 {
108 #ifdef ENABLE_THREAD_SAFETY
109 
110  /*
111  * Disallow changing the flags while we have open connections, else we'd
112  * get completely confused.
113  */
114  if (crypto_open_connections != 0)
115  return;
116 #endif
117 
118  pq_init_ssl_lib = do_ssl;
119  pq_init_crypto_lib = do_crypto;
120 }
static bool pq_init_ssl_lib
static bool pq_init_crypto_lib

◆ pgtls_open_client()

PostgresPollingStatusType pgtls_open_client ( PGconn conn)

Definition at line 123 of file fe-secure-openssl.c.

References initialize_SSL(), open_client_SSL(), PGRES_POLLING_FAILED, and pgtls_close().

Referenced by pqsecure_open_client().

124 {
125  /* First time through? */
126  if (conn->ssl == NULL)
127  {
128  /*
129  * Create a connection-specific SSL object, and load client
130  * certificate, private key, and trusted CA certs.
131  */
132  if (initialize_SSL(conn) != 0)
133  {
134  /* initialize_SSL already put a message in conn->errorMessage */
135  pgtls_close(conn);
136  return PGRES_POLLING_FAILED;
137  }
138  }
139 
140  /* Begin or continue the actual handshake */
141  return open_client_SSL(conn);
142 }
static PostgresPollingStatusType open_client_SSL(PGconn *)
static int initialize_SSL(PGconn *conn)
void pgtls_close(PGconn *conn)

◆ pgtls_read()

ssize_t pgtls_read ( PGconn conn,
void *  ptr,
size_t  len 
)

Definition at line 145 of file fe-secure-openssl.c.

References appendPQExpBuffer(), appendPQExpBufferStr(), ECONNRESET, pg_conn::errorMessage, libpq_gettext, PG_STRERROR_R_BUFLEN, SOCK_ERRNO, SOCK_ERRNO_SET, SOCK_STRERROR, SSLerrfree(), and SSLerrmessage().

Referenced by pqsecure_read().

146 {
147  ssize_t n;
148  int result_errno = 0;
149  char sebuf[PG_STRERROR_R_BUFLEN];
150  int err;
151  unsigned long ecode;
152 
153 rloop:
154 
155  /*
156  * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
157  * queue. In general, the current thread's error queue must be empty
158  * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
159  * not work reliably. Since the possibility exists that other OpenSSL
160  * clients running in the same thread but not under our control will fail
161  * to call ERR_get_error() themselves (after their own I/O operations),
162  * pro-actively clear the per-thread error queue now.
163  */
164  SOCK_ERRNO_SET(0);
165  ERR_clear_error();
166  n = SSL_read(conn->ssl, ptr, len);
167  err = SSL_get_error(conn->ssl, n);
168 
169  /*
170  * Other clients of OpenSSL may fail to call ERR_get_error(), but we
171  * always do, so as to not cause problems for OpenSSL clients that don't
172  * call ERR_clear_error() defensively. Be sure that this happens by
173  * calling now. SSL_get_error() relies on the OpenSSL per-thread error
174  * queue being intact, so this is the earliest possible point
175  * ERR_get_error() may be called.
176  */
177  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
178  switch (err)
179  {
180  case SSL_ERROR_NONE:
181  if (n < 0)
182  {
183  /* Not supposed to happen, so we don't translate the msg */
185  "SSL_read failed but did not provide error information\n");
186  /* assume the connection is broken */
187  result_errno = ECONNRESET;
188  }
189  break;
190  case SSL_ERROR_WANT_READ:
191  n = 0;
192  break;
193  case SSL_ERROR_WANT_WRITE:
194 
195  /*
196  * Returning 0 here would cause caller to wait for read-ready,
197  * which is not correct since what SSL wants is wait for
198  * write-ready. The former could get us stuck in an infinite
199  * wait, so don't risk it; busy-loop instead.
200  */
201  goto rloop;
202  case SSL_ERROR_SYSCALL:
203  if (n < 0)
204  {
205  result_errno = SOCK_ERRNO;
206  if (result_errno == EPIPE ||
207  result_errno == ECONNRESET)
209  libpq_gettext("server closed the connection unexpectedly\n"
210  "\tThis probably means the server terminated abnormally\n"
211  "\tbefore or while processing the request.\n"));
212  else
214  libpq_gettext("SSL SYSCALL error: %s\n"),
215  SOCK_STRERROR(result_errno,
216  sebuf, sizeof(sebuf)));
217  }
218  else
219  {
221  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
222  /* assume the connection is broken */
223  result_errno = ECONNRESET;
224  n = -1;
225  }
226  break;
227  case SSL_ERROR_SSL:
228  {
229  char *errm = SSLerrmessage(ecode);
230 
232  libpq_gettext("SSL error: %s\n"), errm);
233  SSLerrfree(errm);
234  /* assume the connection is broken */
235  result_errno = ECONNRESET;
236  n = -1;
237  break;
238  }
239  case SSL_ERROR_ZERO_RETURN:
240 
241  /*
242  * Per OpenSSL documentation, this error code is only returned for
243  * a clean connection closure, so we should not report it as a
244  * server crash.
245  */
247  libpq_gettext("SSL connection has been closed unexpectedly\n"));
248  result_errno = ECONNRESET;
249  n = -1;
250  break;
251  default:
253  libpq_gettext("unrecognized SSL error code: %d\n"),
254  err);
255  /* assume the connection is broken */
256  result_errno = ECONNRESET;
257  n = -1;
258  break;
259  }
260 
261  /* ensure we return the intended errno to caller */
262  SOCK_ERRNO_SET(result_errno);
263 
264  return n;
265 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define PG_STRERROR_R_BUFLEN
Definition: port.h:235
#define SOCK_STRERROR
Definition: libpq-int.h:855
#define SOCK_ERRNO
Definition: libpq-int.h:854
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:856
static void SSLerrfree(char *buf)
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#define ECONNRESET
Definition: win32_port.h:361
static char * SSLerrmessage(unsigned long ecode)
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ pgtls_read_pending()

bool pgtls_read_pending ( PGconn conn)

Definition at line 268 of file fe-secure-openssl.c.

Referenced by pqSocketCheck().

269 {
270  return SSL_pending(conn->ssl) > 0;
271 }

◆ pgtls_verify_peer_name_matches_certificate_guts()

int pgtls_verify_peer_name_matches_certificate_guts ( PGconn conn,
int *  names_examined,
char **  first_name 
)

Definition at line 512 of file fe-secure-openssl.c.

References Assert, free, i, mode, name, openssl_verify_peer_name_matches_certificate_name(), pthread_mutex_lock(), pthread_mutex_unlock(), and pthread_self().

Referenced by pq_verify_peer_name_matches_certificate().

515 {
516  STACK_OF(GENERAL_NAME) * peer_san;
517  int i;
518  int rc = 0;
519 
520  /*
521  * First, get the Subject Alternative Names (SANs) from the certificate,
522  * and compare them against the originally given hostname.
523  */
524  peer_san = (STACK_OF(GENERAL_NAME) *)
525  X509_get_ext_d2i(conn->peer, NID_subject_alt_name, NULL, NULL);
526 
527  if (peer_san)
528  {
529  int san_len = sk_GENERAL_NAME_num(peer_san);
530 
531  for (i = 0; i < san_len; i++)
532  {
533  const GENERAL_NAME *name = sk_GENERAL_NAME_value(peer_san, i);
534 
535  if (name->type == GEN_DNS)
536  {
537  char *alt_name;
538 
539  (*names_examined)++;
541  name->d.dNSName,
542  &alt_name);
543 
544  if (alt_name)
545  {
546  if (!*first_name)
547  *first_name = alt_name;
548  else
549  free(alt_name);
550  }
551  }
552  if (rc != 0)
553  break;
554  }
555  sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
556  }
557 
558  /*
559  * If there is no subjectAltName extension of type dNSName, check the
560  * Common Name.
561  *
562  * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
563  * dNSName is present, the CN must be ignored.)
564  */
565  if (*names_examined == 0)
566  {
567  X509_NAME *subject_name;
568 
569  subject_name = X509_get_subject_name(conn->peer);
570  if (subject_name != NULL)
571  {
572  int cn_index;
573 
574  cn_index = X509_NAME_get_index_by_NID(subject_name,
575  NID_commonName, -1);
576  if (cn_index >= 0)
577  {
578  (*names_examined)++;
580  X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
581  first_name);
582  }
583  }
584  }
585 
586  return rc;
587 }
static int openssl_verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name, char **store_name)
#define free(a)
Definition: header.h:65
const char * name
Definition: encode.c:561
int i

◆ pgtls_write()

ssize_t pgtls_write ( PGconn conn,
const void *  ptr,
size_t  len 
)

Definition at line 274 of file fe-secure-openssl.c.

References appendPQExpBuffer(), appendPQExpBufferStr(), conn, ECONNRESET, pg_conn::errorMessage, hash(), libpq_gettext, malloc, PG_STRERROR_R_BUFLEN, SOCK_ERRNO, SOCK_ERRNO_SET, SOCK_STRERROR, SSLerrfree(), and SSLerrmessage().

Referenced by pqsecure_write().

275 {
276  ssize_t n;
277  int result_errno = 0;
278  char sebuf[PG_STRERROR_R_BUFLEN];
279  int err;
280  unsigned long ecode;
281 
282  SOCK_ERRNO_SET(0);
283  ERR_clear_error();
284  n = SSL_write(conn->ssl, ptr, len);
285  err = SSL_get_error(conn->ssl, n);
286  ecode = (err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
287  switch (err)
288  {
289  case SSL_ERROR_NONE:
290  if (n < 0)
291  {
292  /* Not supposed to happen, so we don't translate the msg */
294  "SSL_write failed but did not provide error information\n");
295  /* assume the connection is broken */
296  result_errno = ECONNRESET;
297  }
298  break;
299  case SSL_ERROR_WANT_READ:
300 
301  /*
302  * Returning 0 here causes caller to wait for write-ready, which
303  * is not really the right thing, but it's the best we can do.
304  */
305  n = 0;
306  break;
307  case SSL_ERROR_WANT_WRITE:
308  n = 0;
309  break;
310  case SSL_ERROR_SYSCALL:
311  if (n < 0)
312  {
313  result_errno = SOCK_ERRNO;
314  if (result_errno == EPIPE || result_errno == ECONNRESET)
316  libpq_gettext("server closed the connection unexpectedly\n"
317  "\tThis probably means the server terminated abnormally\n"
318  "\tbefore or while processing the request.\n"));
319  else
321  libpq_gettext("SSL SYSCALL error: %s\n"),
322  SOCK_STRERROR(result_errno,
323  sebuf, sizeof(sebuf)));
324  }
325  else
326  {
328  libpq_gettext("SSL SYSCALL error: EOF detected\n"));
329  /* assume the connection is broken */
330  result_errno = ECONNRESET;
331  n = -1;
332  }
333  break;
334  case SSL_ERROR_SSL:
335  {
336  char *errm = SSLerrmessage(ecode);
337 
339  libpq_gettext("SSL error: %s\n"), errm);
340  SSLerrfree(errm);
341  /* assume the connection is broken */
342  result_errno = ECONNRESET;
343  n = -1;
344  break;
345  }
346  case SSL_ERROR_ZERO_RETURN:
347 
348  /*
349  * Per OpenSSL documentation, this error code is only returned for
350  * a clean connection closure, so we should not report it as a
351  * server crash.
352  */
354  libpq_gettext("SSL connection has been closed unexpectedly\n"));
355  result_errno = ECONNRESET;
356  n = -1;
357  break;
358  default:
360  libpq_gettext("unrecognized SSL error code: %d\n"),
361  err);
362  /* assume the connection is broken */
363  result_errno = ECONNRESET;
364  n = -1;
365  break;
366  }
367 
368  /* ensure we return the intended errno to caller */
369  SOCK_ERRNO_SET(result_errno);
370 
371  return n;
372 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:369
#define PG_STRERROR_R_BUFLEN
Definition: port.h:235
#define SOCK_STRERROR
Definition: libpq-int.h:855
#define SOCK_ERRNO
Definition: libpq-int.h:854
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267
#define SOCK_ERRNO_SET(e)
Definition: libpq-int.h:856
static void SSLerrfree(char *buf)
PQExpBufferData errorMessage
Definition: libpq-int.h:571
#define ECONNRESET
Definition: win32_port.h:361
static char * SSLerrmessage(unsigned long ecode)
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQdefaultSSLKeyPassHook_OpenSSL()

int PQdefaultSSLKeyPassHook_OpenSSL ( char *  buf,
int  size,
PGconn conn 
)

Definition at line 1778 of file fe-secure-openssl.c.

Referenced by PQssl_passwd_cb().

1779 {
1780  if (conn->sslpassword)
1781  {
1782  if (strlen(conn->sslpassword) + 1 > size)
1783  fprintf(stderr, libpq_gettext("WARNING: sslpassword truncated\n"));
1784  strncpy(buf, conn->sslpassword, size);
1785  buf[size - 1] = '\0';
1786  return strlen(buf);
1787  }
1788  else
1789  {
1790  buf[0] = '\0';
1791  return 0;
1792  }
1793 }
#define fprintf
Definition: port.h:221
static char * buf
Definition: pg_test_fsync.c:68
char * sslpassword
Definition: libpq-int.h:383
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ PQgetssl()

void* PQgetssl ( PGconn conn)

Definition at line 1554 of file fe-secure-openssl.c.

1555 {
1556  if (!conn)
1557  return NULL;
1558  return conn->ssl;
1559 }

◆ PQgetSSLKeyPassHook_OpenSSL()

PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL ( void  )

Definition at line 1796 of file fe-secure-openssl.c.

1797 {
1798  return PQsslKeyPassHook;
1799 }
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook

◆ PQsetSSLKeyPassHook_OpenSSL()

void PQsetSSLKeyPassHook_OpenSSL ( PQsslKeyPassHook_OpenSSL_type  hook)

Definition at line 1802 of file fe-secure-openssl.c.

1803 {
1804  PQsslKeyPassHook = hook;
1805 }
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook

◆ PQssl_passwd_cb()

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

Definition at line 1813 of file fe-secure-openssl.c.

References PQdefaultSSLKeyPassHook_OpenSSL(), and PQsslKeyPassHook.

Referenced by initialize_SSL().

1814 {
1815  PGconn *conn = userdata;
1816 
1817  if (PQsslKeyPassHook)
1818  return PQsslKeyPassHook(buf, size, conn);
1819  else
1820  return PQdefaultSSLKeyPassHook_OpenSSL(buf, size, conn);
1821 }
int PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook
PGconn * conn
Definition: streamutil.c:54
static char * buf
Definition: pg_test_fsync.c:68

◆ PQsslAttribute()

const char* PQsslAttribute ( PGconn conn,
const char *  attribute_name 
)

Definition at line 1587 of file fe-secure-openssl.c.

Referenced by printSSLInfo().

1588 {
1589  if (!conn)
1590  return NULL;
1591  if (conn->ssl == NULL)
1592  return NULL;
1593 
1594  if (strcmp(attribute_name, "library") == 0)
1595  return "OpenSSL";
1596 
1597  if (strcmp(attribute_name, "key_bits") == 0)
1598  {
1599  static char sslbits_str[12];
1600  int sslbits;
1601 
1602  SSL_get_cipher_bits(conn->ssl, &sslbits);
1603  snprintf(sslbits_str, sizeof(sslbits_str), "%d", sslbits);
1604  return sslbits_str;
1605  }
1606 
1607  if (strcmp(attribute_name, "cipher") == 0)
1608  return SSL_get_cipher(conn->ssl);
1609 
1610  if (strcmp(attribute_name, "compression") == 0)
1611  return SSL_get_current_compression(conn->ssl) ? "on" : "off";
1612 
1613  if (strcmp(attribute_name, "protocol") == 0)
1614  return SSL_get_version(conn->ssl);
1615 
1616  return NULL; /* unknown attribute */
1617 }
#define snprintf
Definition: port.h:217

◆ PQsslAttributeNames()

const char* const* PQsslAttributeNames ( PGconn conn)

Definition at line 1572 of file fe-secure-openssl.c.

1573 {
1574  static const char *const result[] = {
1575  "library",
1576  "key_bits",
1577  "cipher",
1578  "compression",
1579  "protocol",
1580  NULL
1581  };
1582 
1583  return result;
1584 }

◆ PQsslStruct()

void* PQsslStruct ( PGconn conn,
const char *  struct_name 
)

Definition at line 1562 of file fe-secure-openssl.c.

1563 {
1564  if (!conn)
1565  return NULL;
1566  if (strcmp(struct_name, "OpenSSL") == 0)
1567  return conn->ssl;
1568  return NULL;
1569 }

◆ ssl_protocol_version_to_openssl()

static int ssl_protocol_version_to_openssl ( const char *  protocol)
static

Definition at line 1834 of file fe-secure-openssl.c.

References pg_strcasecmp().

Referenced by initialize_SSL().

1835 {
1836  if (pg_strcasecmp("TLSv1", protocol) == 0)
1837  return TLS1_VERSION;
1838 
1839 #ifdef TLS1_1_VERSION
1840  if (pg_strcasecmp("TLSv1.1", protocol) == 0)
1841  return TLS1_1_VERSION;
1842 #endif
1843 
1844 #ifdef TLS1_2_VERSION
1845  if (pg_strcasecmp("TLSv1.2", protocol) == 0)
1846  return TLS1_2_VERSION;
1847 #endif
1848 
1849 #ifdef TLS1_3_VERSION
1850  if (pg_strcasecmp("TLSv1.3", protocol) == 0)
1851  return TLS1_3_VERSION;
1852 #endif
1853 
1854  return -1;
1855 }
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36

◆ SSLerrfree()

static void SSLerrfree ( char *  buf)
static

Definition at line 1540 of file fe-secure-openssl.c.

References free, and ssl_nomem.

Referenced by initialize_SSL(), open_client_SSL(), pgtls_read(), and pgtls_write().

1541 {
1542  if (buf != ssl_nomem)
1543  free(buf);
1544 }
static char ssl_nomem[]
static char * buf
Definition: pg_test_fsync.c:68
#define free(a)
Definition: header.h:65

◆ SSLerrmessage()

static char * SSLerrmessage ( unsigned long  ecode)
static

Definition at line 1516 of file fe-secure-openssl.c.

References libpq_gettext, malloc, snprintf, SSL_ERR_LEN, ssl_nomem, and strlcpy().

Referenced by initialize_SSL(), open_client_SSL(), pgtls_read(), and pgtls_write().

1517 {
1518  const char *errreason;
1519  char *errbuf;
1520 
1521  errbuf = malloc(SSL_ERR_LEN);
1522  if (!errbuf)
1523  return ssl_nomem;
1524  if (ecode == 0)
1525  {
1526  snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("no SSL error reported"));
1527  return errbuf;
1528  }
1529  errreason = ERR_reason_error_string(ecode);
1530  if (errreason != NULL)
1531  {
1532  strlcpy(errbuf, errreason, SSL_ERR_LEN);
1533  return errbuf;
1534  }
1535  snprintf(errbuf, SSL_ERR_LEN, libpq_gettext("SSL error code %lu"), ecode);
1536  return errbuf;
1537 }
#define malloc(a)
Definition: header.h:50
static char ssl_nomem[]
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define snprintf
Definition: port.h:217
#define SSL_ERR_LEN
#define libpq_gettext(x)
Definition: libpq-int.h:841

◆ verify_cb()

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

Definition at line 466 of file fe-secure-openssl.c.

Referenced by initialize_SSL().

467 {
468  return ok;
469 }

Variable Documentation

◆ my_bio_methods

BIO_METHOD* my_bio_methods
static

Definition at line 1635 of file fe-secure-openssl.c.

Referenced by my_BIO_s_socket().

◆ pq_init_crypto_lib

bool pq_init_crypto_lib = true
static

Definition at line 83 of file fe-secure-openssl.c.

Referenced by destroy_ssl_system(), pgtls_init(), and pgtls_init_library().

◆ pq_init_ssl_lib

bool pq_init_ssl_lib = true
static

Definition at line 82 of file fe-secure-openssl.c.

Referenced by pgtls_init(), and pgtls_init_library().

◆ PQsslKeyPassHook

◆ ssl_lib_initialized

bool ssl_lib_initialized = false
static

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

Referenced by pgtls_init().

◆ ssl_nomem

char ssl_nomem[] = "out of memory allocating error description"
static

Definition at line 1511 of file fe-secure-openssl.c.

Referenced by SSLerrfree(), and SSLerrmessage().