60 #include <openssl/conf.h>
62 #include <openssl/engine.h>
64 #include <openssl/x509v3.h>
67 static int verify_cb(
int ok, X509_STORE_CTX *ctx);
69 ASN1_STRING *name_entry,
72 ASN1_OCTET_STRING *addr_entry,
98 if (
conn->ssl == NULL)
120 int result_errno = 0;
138 n = SSL_read(
conn->ssl, ptr,
len);
139 err = SSL_get_error(
conn->ssl, n);
149 ecode = (
err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
157 "SSL_read failed but did not provide error information\n");
162 case SSL_ERROR_WANT_READ:
165 case SSL_ERROR_WANT_WRITE:
174 case SSL_ERROR_SYSCALL:
178 if (result_errno == EPIPE ||
181 "\tThis probably means the server terminated abnormally\n"
182 "\tbefore or while processing the request.");
186 sebuf,
sizeof(sebuf)));
207 case SSL_ERROR_ZERO_RETURN:
235 return SSL_pending(
conn->ssl) > 0;
242 int result_errno = 0;
249 n = SSL_write(
conn->ssl, ptr,
len);
250 err = SSL_get_error(
conn->ssl, n);
251 ecode = (
err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
259 "SSL_write failed but did not provide error information\n");
264 case SSL_ERROR_WANT_READ:
272 case SSL_ERROR_WANT_WRITE:
275 case SSL_ERROR_SYSCALL:
285 if (result_errno == EPIPE || result_errno ==
ECONNRESET)
287 "\tThis probably means the server terminated abnormally\n"
288 "\tbefore or while processing the request.");
292 sebuf,
sizeof(sebuf)));
313 case SSL_ERROR_ZERO_RETURN:
342 const EVP_MD *algo_type;
343 unsigned char hash[EVP_MAX_MD_SIZE];
344 unsigned int hash_size;
353 peer_cert =
conn->peer;
360 #if HAVE_X509_GET_SIGNATURE_INFO
361 if (!X509_get_signature_info(peer_cert, &algo_nid, NULL, NULL, NULL))
363 if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert),
381 algo_type = EVP_sha256();
384 algo_type = EVP_get_digestbynid(algo_nid);
385 if (algo_type == NULL)
388 OBJ_nid2sn(algo_nid));
394 if (!X509_digest(peer_cert, algo_type,
hash, &hash_size))
401 cert_hash =
malloc(hash_size);
402 if (cert_hash == NULL)
407 memcpy(cert_hash,
hash, hash_size);
434 #ifdef HAVE_SSL_CTX_SET_CERT_CB
445 cert_cb(SSL *ssl,
void *
arg)
452 if (SSL_get_certificate(ssl))
473 const unsigned char *namedata;
476 if (name_entry == NULL)
485 namedata = ASN1_STRING_get0_data(name_entry);
486 len = ASN1_STRING_length(name_entry);
499 ASN1_OCTET_STRING *addr_entry,
503 const unsigned char *addrdata;
506 if (addr_entry == NULL)
516 addrdata = ASN1_STRING_get0_data(addr_entry);
517 len = ASN1_STRING_length(addr_entry);
525 struct in_addr dummy4;
526 #ifdef HAVE_INET_PTON
527 struct in6_addr dummy6;
531 #ifdef HAVE_INET_PTON
532 || (inet_pton(AF_INET6, host, &dummy6) == 1)
547 STACK_OF(GENERAL_NAME) * peer_san;
552 bool check_cn =
true;
577 host_type = GEN_IPADD;
585 peer_san = (STACK_OF(GENERAL_NAME) *)
586 X509_get_ext_d2i(
conn->peer, NID_subject_alt_name, NULL, NULL);
590 int san_len = sk_GENERAL_NAME_num(peer_san);
592 for (
i = 0;
i < san_len;
i++)
594 const GENERAL_NAME *
name = sk_GENERAL_NAME_value(peer_san,
i);
595 char *alt_name = NULL;
597 if (
name->type == host_type)
606 if (
name->type == GEN_DNS)
613 else if (
name->type == GEN_IPADD)
624 *first_name = alt_name;
639 sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
652 X509_NAME *subject_name;
654 subject_name = X509_get_subject_name(
conn->peer);
655 if (subject_name != NULL)
659 cn_index = X509_NAME_get_index_by_NID(subject_name,
663 char *common_name = NULL;
667 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
673 *first_name = common_name;
717 have_homedir =
false;
755 #ifdef HAVE_SSL_CTX_SET_CERT_CB
761 SSL_CTX_set_options(
SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
771 if (ssl_min_ver == -1)
779 if (!SSL_CTX_set_min_proto_version(
SSL_context, ssl_min_ver))
797 if (ssl_max_ver == -1)
805 if (!SSL_CTX_set_max_proto_version(
SSL_context, ssl_max_ver))
820 SSL_CTX_set_mode(
SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
829 else if (have_homedir)
830 snprintf(fnbuf,
sizeof(fnbuf),
"%s/%s", homedir, ROOT_CERT_FILE);
834 if (strcmp(fnbuf,
"system") == 0)
843 if (SSL_CTX_set_default_verify_paths(
SSL_context) != 1)
853 have_rootcert =
true;
855 else if (fnbuf[0] !=
'\0' &&
860 if (SSL_CTX_load_verify_locations(
SSL_context, fnbuf, NULL) != 1)
871 if ((cvstore = SSL_CTX_get_cert_store(
SSL_context)) != NULL)
882 if (!fname && !dname && have_homedir)
884 snprintf(fnbuf,
sizeof(fnbuf),
"%s/%s", homedir, ROOT_CRL_FILE);
889 if ((fname || dname) &&
890 X509_STORE_load_locations(cvstore, fname, dname) == 1)
892 X509_STORE_set_flags(cvstore,
893 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
899 have_rootcert =
true;
915 if (fnbuf[0] ==
'\0')
917 "Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.");
920 "Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.", fnbuf);
924 have_rootcert =
false;
930 else if (have_homedir)
931 snprintf(fnbuf,
sizeof(fnbuf),
"%s/%s", homedir, USER_CERT_FILE);
940 else if (fnbuf[0] ==
'\0')
945 else if (
stat(fnbuf, &
buf) != 0)
952 if (errno != ENOENT && errno != ENOTDIR)
955 fnbuf,
strerror_r(errno, sebuf,
sizeof(sebuf)));
968 if (SSL_CTX_use_certificate_chain_file(
SSL_context, fnbuf) != 1)
991 !SSL_set_app_data(
conn->ssl,
conn) ||
1020 if (host && host[0] &&
1021 !(strspn(host,
"0123456789.") == strlen(host) ||
1024 if (SSL_set_tlsext_host_name(
conn->ssl, host) != 1)
1059 #ifdef USE_SSL_ENGINE
1071 if (engine_str == NULL)
1078 engine_colon = strchr(engine_str,
':');
1080 *engine_colon =
'\0';
1083 conn->engine = ENGINE_by_id(engine_str);
1084 if (
conn->engine == NULL)
1095 if (ENGINE_init(
conn->engine) == 0)
1102 ENGINE_free(
conn->engine);
1103 conn->engine = NULL;
1108 pkey = ENGINE_load_private_key(
conn->engine, engine_colon,
1115 engine_colon, engine_str,
err);
1117 ENGINE_finish(
conn->engine);
1118 ENGINE_free(
conn->engine);
1119 conn->engine = NULL;
1123 if (SSL_use_PrivateKey(
conn->ssl, pkey) != 1)
1128 engine_colon, engine_str,
err);
1130 ENGINE_finish(
conn->engine);
1131 ENGINE_free(
conn->engine);
1132 conn->engine = NULL;
1149 else if (have_homedir)
1152 snprintf(fnbuf,
sizeof(fnbuf),
"%s/%s", homedir, USER_KEY_FILE);
1157 if (have_cert && fnbuf[0] !=
'\0')
1163 if (errno == ENOENT)
1202 #if !defined(WIN32) && !defined(__CYGWIN__)
1203 if (
buf.st_uid == 0 ?
1208 "private key file \"%s\" has group or world access; file must have permissions u=rw (0600) or less if owned by the current user, or permissions u=rw,g=r (0640) or less if owned by root",
1214 if (SSL_use_PrivateKey_file(
conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1230 if (SSL_use_PrivateKey_file(
conn->ssl, fnbuf, SSL_FILETYPE_ASN1) != 1)
1244 SSL_check_private_key(
conn->ssl) != 1)
1265 SSL_set_options(
conn->ssl, SSL_OP_NO_COMPRESSION);
1267 SSL_clear_options(
conn->ssl, SSL_OP_NO_COMPRESSION);
1282 r = SSL_connect(
conn->ssl);
1286 int err = SSL_get_error(
conn->ssl, r);
1287 unsigned long ecode;
1289 ecode = ERR_get_error();
1292 case SSL_ERROR_WANT_READ:
1295 case SSL_ERROR_WANT_WRITE:
1298 case SSL_ERROR_SYSCALL:
1301 unsigned long vcode;
1303 vcode = SSL_get_verify_result(
conn->ssl);
1314 if (save_errno == 0 &&
1315 vcode == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY &&
1318 X509_verify_cert_error_string(vcode));
1319 else if (r == -1 && save_errno != 0)
1333 switch (ERR_GET_REASON(ecode))
1349 case SSL_R_NO_PROTOCOLS_AVAILABLE:
1350 case SSL_R_UNSUPPORTED_PROTOCOL:
1351 case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
1352 case SSL_R_UNKNOWN_PROTOCOL:
1353 case SSL_R_UNKNOWN_SSL_VERSION:
1354 case SSL_R_UNSUPPORTED_SSL_VERSION:
1355 case SSL_R_WRONG_SSL_VERSION:
1356 case SSL_R_WRONG_VERSION_NUMBER:
1357 case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
1358 #ifdef SSL_R_VERSION_TOO_HIGH
1359 case SSL_R_VERSION_TOO_HIGH:
1360 case SSL_R_VERSION_TOO_LOW:
1365 MIN_OPENSSL_TLS_VERSION,
1368 MAX_OPENSSL_TLS_VERSION);
1387 const unsigned char *selected;
1390 SSL_get0_alpn_selected(
conn->ssl, &selected, &
len);
1392 if (selected == NULL)
1418 conn->peer = SSL_get_peer_certificate(
conn->ssl);
1419 if (
conn->peer == NULL)
1452 SSL_shutdown(
conn->ssl);
1453 SSL_free(
conn->ssl);
1461 X509_free(
conn->peer);
1465 #ifdef USE_SSL_ENGINE
1468 ENGINE_finish(
conn->engine);
1469 ENGINE_free(
conn->engine);
1470 conn->engine = NULL;
1487 static char ssl_nomem[] =
"out of memory allocating error description";
1489 #define SSL_ERR_LEN 128
1494 const char *errreason;
1505 errreason = ERR_reason_error_string(ecode);
1506 if (errreason != NULL)
1520 #ifdef SSL_AD_NO_APPLICATION_PROTOCOL
1521 if (ERR_GET_LIB(ecode) == ERR_LIB_SSL &&
1522 ERR_GET_REASON(ecode) == SSL_AD_REASON_OFFSET + SSL_AD_NO_APPLICATION_PROTOCOL)
1536 #ifdef ERR_SYSTEM_ERROR
1537 if (ERR_SYSTEM_ERROR(ecode))
1576 if (strcmp(struct_name,
"OpenSSL") == 0)
1584 static const char *
const openssl_attrs[] = {
1593 static const char *
const empty_attrs[] = {NULL};
1598 return openssl_attrs;
1602 if (
conn->ssl == NULL)
1605 return openssl_attrs;
1614 if (strcmp(attribute_name,
"library") == 0)
1620 if (
conn->ssl == NULL)
1623 if (strcmp(attribute_name,
"library") == 0)
1626 if (strcmp(attribute_name,
"key_bits") == 0)
1628 static char sslbits_str[12];
1631 SSL_get_cipher_bits(
conn->ssl, &sslbits);
1632 snprintf(sslbits_str,
sizeof(sslbits_str),
"%d", sslbits);
1636 if (strcmp(attribute_name,
"cipher") == 0)
1637 return SSL_get_cipher(
conn->ssl);
1639 if (strcmp(attribute_name,
"compression") == 0)
1640 return SSL_get_current_compression(
conn->ssl) ?
"on" :
"off";
1642 if (strcmp(attribute_name,
"protocol") == 0)
1643 return SSL_get_version(
conn->ssl);
1645 if (strcmp(attribute_name,
"alpn") == 0)
1647 const unsigned char *
data;
1649 static char alpn_str[256];
1653 if (
data == NULL ||
len == 0 ||
len >
sizeof(alpn_str) - 1)
1682 BIO_clear_retry_flags(h);
1691 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1695 BIO_set_retry_read(h);
1715 BIO_clear_retry_flags(h);
1724 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1728 BIO_set_retry_write(h);
1751 BIO_METHOD *biom = (BIO_METHOD *) BIO_s_socket();
1754 my_bio_index = BIO_get_new_index();
1755 if (my_bio_index == -1)
1757 my_bio_index |= (BIO_TYPE_DESCRIPTOR | BIO_TYPE_SOURCE_SINK);
1758 res = BIO_meth_new(my_bio_index,
"libpq socket");
1768 !BIO_meth_set_gets(
res, BIO_meth_get_gets(biom)) ||
1769 !BIO_meth_set_puts(
res, BIO_meth_get_puts(biom)) ||
1770 !BIO_meth_set_ctrl(
res, BIO_meth_get_ctrl(biom)) ||
1771 !BIO_meth_set_create(
res, BIO_meth_get_create(biom)) ||
1772 !BIO_meth_set_destroy(
res, BIO_meth_get_destroy(biom)) ||
1773 !BIO_meth_set_callback_ctrl(
res, BIO_meth_get_callback_ctrl(biom)))
1796 BIO_METHOD *bio_method;
1799 if (bio_method == NULL)
1801 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1804 bio = BIO_new(bio_method);
1807 SSLerr(SSL_F_SSL_SET_FD, ERR_R_BUF_LIB);
1810 BIO_set_app_data(bio,
conn);
1812 SSL_set_bio(
conn->ssl, bio, bio);
1813 BIO_set_fd(bio,
fd, BIO_NOCLOSE);
1884 return TLS1_VERSION;
1886 #ifdef TLS1_1_VERSION
1888 return TLS1_1_VERSION;
1891 #ifdef TLS1_2_VERSION
1893 return TLS1_2_VERSION;
1896 #ifdef TLS1_3_VERSION
1898 return TLS1_3_VERSION;
static SSL_CTX * SSL_context
#define Assert(condition)
static void PGresult * res
void err(int eval, const char *fmt,...)
bool pqGetHomeDirectory(char *buf, int bufsize)
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
int pq_verify_peer_name_matches_certificate_name(PGconn *conn, const char *namedata, size_t namelen, char **store_name)
int pq_verify_peer_name_matches_certificate_ip(PGconn *conn, const unsigned char *ipdata, size_t iplen, char **store_name)
bool pq_verify_peer_name_matches_certificate(PGconn *conn)
static int ssl_protocol_version_to_openssl(const char *protocol)
static int my_SSL_set_fd(PGconn *conn, int fd)
static void SSLerrfree(char *buf)
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void)
int pgtls_verify_peer_name_matches_certificate_guts(PGconn *conn, int *names_examined, char **first_name)
PostgresPollingStatusType pgtls_open_client(PGconn *conn)
bool pgtls_read_pending(PGconn *conn)
int PQdefaultSSLKeyPassHook_OpenSSL(char *buf, int size, PGconn *conn)
static BIO_METHOD * my_bio_methods
static int openssl_verify_peer_name_matches_certificate_name(PGconn *conn, ASN1_STRING *name_entry, char **store_name)
ssize_t pgtls_read(PGconn *conn, void *ptr, size_t len)
ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len)
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook
static BIO_METHOD * my_BIO_s_socket(void)
const char *const * PQsslAttributeNames(PGconn *conn)
void * PQgetssl(PGconn *conn)
void * PQsslStruct(PGconn *conn, const char *struct_name)
static int initialize_SSL(PGconn *conn)
static pthread_mutex_t ssl_config_mutex
static int verify_cb(int ok, X509_STORE_CTX *ctx)
static int PQssl_passwd_cb(char *buf, int size, int rwflag, void *userdata)
static char * SSLerrmessage(unsigned long ecode)
static int openssl_verify_peer_name_matches_certificate_ip(PGconn *conn, ASN1_OCTET_STRING *addr_entry, char **store_name)
char * pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
static PostgresPollingStatusType open_client_SSL(PGconn *conn)
const char * PQsslAttribute(PGconn *conn, const char *attribute_name)
static unsigned char alpn_protos[]
void pgtls_close(PGconn *conn)
void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook)
static int my_sock_write(BIO *h, const char *buf, int size)
static int my_sock_read(BIO *h, char *buf, int size)
static bool is_ip_address(const char *host)
ssize_t pqsecure_raw_read(PGconn *conn, void *ptr, size_t len)
ssize_t pqsecure_raw_write(PGconn *conn, const void *ptr, size_t len)
int(* PQsslKeyPassHook_OpenSSL_type)(char *buf, int size, PGconn *conn)
PostgresPollingStatusType
#define SOCK_ERRNO_SET(e)
#define PG_STRERROR_R_BUFLEN
int pg_strcasecmp(const char *s1, const char *s2)
int inet_aton(const char *cp, struct in_addr *addr)
size_t strlcpy(char *dst, const char *src, size_t siz)
#define PG_ALPN_PROTOCOL_VECTOR
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
static int fd(const char *x, int i)
int pthread_mutex_unlock(pthread_mutex_t *mp)
int pthread_mutex_lock(pthread_mutex_t *mp)
#define PTHREAD_MUTEX_INITIALIZER
static unsigned hash(unsigned *uv, int n)
static pg_noinline void Size size
char * ssl_max_protocol_version
char * ssl_min_protocol_version
PQExpBufferData errorMessage
bool ssl_handshake_started