1/*-------------------------------------------------------------------------
7 * Portions Copyright (c) 1996-2025, PostgreSQL Global Development Group
8 * Portions Copyright (c) 1994, Regents of the University of California
12 * src/interfaces/libpq/fe-secure-openssl.c
16 * We don't provide informational callbacks here (like
17 * info_cb() in be-secure-openssl.c), since there's no good mechanism to
18 * display such information to the user.
20 *-------------------------------------------------------------------------
54 * These SSL-related #includes must come after all system-provided headers.
55 * This ensures that OpenSSL can take care of conflicts with Windows'
56 * <wincrypt.h> by #undef'ing the conflicting macros. (We don't directly
57 * include <wincrypt.h>, but some other Windows headers do.)
60#include <openssl/ssl.h>
61#include <openssl/conf.h>
63#include <openssl/engine.h>
65#include <openssl/x509v3.h>
68static int verify_cb(
int ok, X509_STORE_CTX *ctx);
70 ASN1_STRING *name_entry,
73 ASN1_OCTET_STRING *addr_entry,
91/* ------------------------------------------------------------ */
92/* Procedures common to all secure sessions */
93/* ------------------------------------------------------------ */
98 /* First time through? */
99 if (
conn->ssl == NULL)
102 * Create a connection-specific SSL object, and load client
103 * certificate, private key, and trusted CA certs.
107 /* initialize_SSL already put a message in conn->errorMessage */
113 /* Begin or continue the actual handshake */
121 int result_errno = 0;
129 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
130 * queue. In general, the current thread's error queue must be empty
131 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
132 * not work reliably. Since the possibility exists that other OpenSSL
133 * clients running in the same thread but not under our control will fail
134 * to call ERR_get_error() themselves (after their own I/O operations),
135 * pro-actively clear the per-thread error queue now.
139 n = SSL_read(
conn->ssl, ptr,
len);
140 err = SSL_get_error(
conn->ssl, n);
143 * Other clients of OpenSSL may fail to call ERR_get_error(), but we
144 * always do, so as to not cause problems for OpenSSL clients that don't
145 * call ERR_clear_error() defensively. Be sure that this happens by
146 * calling now. SSL_get_error() relies on the OpenSSL per-thread error
147 * queue being intact, so this is the earliest possible point
148 * ERR_get_error() may be called.
150 ecode = (
err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
156 /* Not supposed to happen, so we don't translate the msg */
158 "SSL_read failed but did not provide error information\n");
159 /* assume the connection is broken */
163 case SSL_ERROR_WANT_READ:
166 case SSL_ERROR_WANT_WRITE:
169 * Returning 0 here would cause caller to wait for read-ready,
170 * which is not correct since what SSL wants is wait for
171 * write-ready. The former could get us stuck in an infinite
172 * wait, so don't risk it; busy-loop instead.
175 case SSL_ERROR_SYSCALL:
179 if (result_errno == EPIPE ||
182 "\tThis probably means the server terminated abnormally\n"
183 "\tbefore or while processing the request.");
187 sebuf,
sizeof(sebuf)));
192 /* assume the connection is broken */
203 /* assume the connection is broken */
208 case SSL_ERROR_ZERO_RETURN:
211 * Per OpenSSL documentation, this error code is only returned for
212 * a clean connection closure, so we should not report it as a
221 /* assume the connection is broken */
227 /* ensure we return the intended errno to caller */
236 return SSL_pending(
conn->ssl) > 0;
243 int result_errno = 0;
250 n = SSL_write(
conn->ssl, ptr,
len);
251 err = SSL_get_error(
conn->ssl, n);
252 ecode = (
err != SSL_ERROR_NONE || n < 0) ? ERR_get_error() : 0;
258 /* Not supposed to happen, so we don't translate the msg */
260 "SSL_write failed but did not provide error information\n");
261 /* assume the connection is broken */
265 case SSL_ERROR_WANT_READ:
268 * Returning 0 here causes caller to wait for write-ready, which
269 * is not really the right thing, but it's the best we can do.
273 case SSL_ERROR_WANT_WRITE:
276 case SSL_ERROR_SYSCALL:
279 * If errno is still zero then assume it's a read EOF situation,
280 * and report EOF. (This seems possible because SSL_write can
286 if (result_errno == EPIPE || result_errno ==
ECONNRESET)
288 "\tThis probably means the server terminated abnormally\n"
289 "\tbefore or while processing the request.");
293 sebuf,
sizeof(sebuf)));
298 /* assume the connection is broken */
309 /* assume the connection is broken */
314 case SSL_ERROR_ZERO_RETURN:
317 * Per OpenSSL documentation, this error code is only returned for
318 * a clean connection closure, so we should not report it as a
327 /* assume the connection is broken */
333 /* ensure we return the intended errno to caller */
343 const EVP_MD *algo_type;
344 unsigned char hash[EVP_MAX_MD_SIZE];
/* size for SHA-512 */
345 unsigned int hash_size;
354 peer_cert =
conn->peer;
357 * Get the signature algorithm of the certificate to determine the hash
358 * algorithm to use for the result. Prefer X509_get_signature_info(),
359 * introduced in OpenSSL 1.1.1, which can handle RSA-PSS signatures.
361#if HAVE_X509_GET_SIGNATURE_INFO
362 if (!X509_get_signature_info(peer_cert, &algo_nid, NULL, NULL, NULL))
364 if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert),
373 * The TLS server's certificate bytes need to be hashed with SHA-256 if
374 * its signature algorithm is MD5 or SHA-1 as per RFC 5929
375 * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
376 * is used, the same hash as the signature algorithm is used.
382 algo_type = EVP_sha256();
385 algo_type = EVP_get_digestbynid(algo_nid);
386 if (algo_type == NULL)
389 OBJ_nid2sn(algo_nid));
395 if (!X509_digest(peer_cert, algo_type,
hash, &hash_size))
402 cert_hash =
malloc(hash_size);
403 if (cert_hash == NULL)
408 memcpy(cert_hash,
hash, hash_size);
414/* ------------------------------------------------------------ */
415/* OpenSSL specific code */
416/* ------------------------------------------------------------ */
419 * Certificate verification callback
421 * This callback allows us to log intermediate problems during
422 * verification, but there doesn't seem to be a clean way to get
423 * our PGconn * structure. So we can't log anything!
425 * This callback also allows us to override the default acceptance
426 * criteria (e.g., accepting self-signed or expired certs), but
427 * for now we accept the default checks.
435#ifdef HAVE_SSL_CTX_SET_CERT_CB
437 * Certificate selection callback
439 * This callback lets us choose the client certificate we send to the server
440 * after seeing its CertificateRequest. We only support sending a single
441 * hard-coded certificate via sslcert, so we don't actually set any certificates
442 * here; we just use it to record whether or not the server has actually asked
443 * for one and whether we have one to send.
446cert_cb(SSL *ssl,
void *
arg)
452 /* Do we have a certificate loaded to send back? */
453 if (SSL_get_certificate(ssl))
457 * Tell OpenSSL that the callback succeeded; we're not required to
458 * actually make any changes to the SSL handle.
465 * OpenSSL-specific wrapper around
466 * pq_verify_peer_name_matches_certificate_name(), converting the ASN1_STRING
467 * into a plain C string.
474 const unsigned char *namedata;
476 /* Should not happen... */
477 if (name_entry == NULL)
484 * GEN_DNS can be only IA5String, equivalent to US ASCII.
486 namedata = ASN1_STRING_get0_data(name_entry);
487 len = ASN1_STRING_length(name_entry);
489 /* OK to cast from unsigned to plain char, since it's all ASCII. */
494 * OpenSSL-specific wrapper around
495 * pq_verify_peer_name_matches_certificate_ip(), converting the
496 * ASN1_OCTET_STRING into a plain C string.
500 ASN1_OCTET_STRING *addr_entry,
504 const unsigned char *addrdata;
506 /* Should not happen... */
507 if (addr_entry == NULL)
514 * GEN_IPADD is an OCTET STRING containing an IP address in network byte
517 addrdata = ASN1_STRING_get0_data(addr_entry);
518 len = ASN1_STRING_length(addr_entry);
526 struct in_addr dummy4;
528 struct in6_addr dummy6;
533 || (inet_pton(AF_INET6, host, &dummy6) == 1)
539 * Verify that the server certificate matches the hostname we connected to.
541 * The certificate's Common Name and Subject Alternative Names are considered.
548 STACK_OF(GENERAL_NAME) * peer_san;
553 bool check_cn =
true;
555 Assert(host && host[0]);
/* should be guaranteed by caller */
558 * We try to match the NSS behavior here, which is a slight departure from
559 * the spec but seems to make more intuitive sense:
561 * If connhost contains a DNS name, and the certificate's SANs contain any
562 * dNSName entries, then we'll ignore the Subject Common Name entirely;
563 * otherwise, we fall back to checking the CN. (This behavior matches the
566 * If connhost contains an IP address, and the SANs contain iPAddress
567 * entries, we again ignore the CN. Otherwise, we allow the CN to match,
568 * EVEN IF there is a dNSName in the SANs. (RFC 6125 prohibits this: "A
569 * client MUST NOT seek a match for a reference identifier of CN-ID if the
570 * presented identifiers include a DNS-ID, SRV-ID, URI-ID, or any
571 * application-specific identifier types supported by the client.")
573 * NOTE: Prior versions of libpq did not consider iPAddress entries at
574 * all, so this new behavior might break a certificate that has different
575 * IP addresses in the Subject CN and the SANs.
578 host_type = GEN_IPADD;
583 * First, get the Subject Alternative Names (SANs) from the certificate,
584 * and compare them against the originally given hostname.
586 peer_san = (STACK_OF(GENERAL_NAME) *)
587 X509_get_ext_d2i(
conn->peer, NID_subject_alt_name, NULL, NULL);
591 int san_len = sk_GENERAL_NAME_num(peer_san);
593 for (
i = 0;
i < san_len;
i++)
595 const GENERAL_NAME *
name = sk_GENERAL_NAME_value(peer_san,
i);
596 char *alt_name = NULL;
598 if (
name->type == host_type)
601 * This SAN is of the same type (IP or DNS) as our host name,
602 * so don't allow a fallback check of the CN.
607 if (
name->type == GEN_DNS)
614 else if (
name->type == GEN_IPADD)
625 *first_name = alt_name;
633 * Either we hit an error or a match, and either way we should
634 * not fall back to the CN.
640 sk_GENERAL_NAME_pop_free(peer_san, GENERAL_NAME_free);
644 * If there is no subjectAltName extension of the matching type, check the
647 * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
648 * dNSName is present, the CN must be ignored. We break this rule if host
649 * is an IP address; see the comment above.)
653 X509_NAME *subject_name;
655 subject_name = X509_get_subject_name(
conn->peer);
656 if (subject_name != NULL)
660 cn_index = X509_NAME_get_index_by_NID(subject_name,
664 char *common_name = NULL;
668 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name, cn_index)),
674 *first_name = common_name;
685/* See pqcomm.h comments on OpenSSL implementation of ALPN (RFC 7301) */
688#ifdef HAVE_SSL_CTX_SET_KEYLOG_CALLBACK
690 * SSL Key Logging callback
692 * This callback lets the user store all key material to a file for debugging
693 * purposes. The file will be written using the NSS keylog format. LibreSSL
694 * 3.5 introduced stub function to set the callback for OpenSSL compatibility
695 * but the callback is never invoked.
697 * Error messages added to the connection object wont be printed anywhere if
698 * the connection is successful. Errors in processing keylogging are printed
699 * to stderr to overcome this.
702SSL_CTX_keylog_cb(
const SSL *ssl,
const char *line)
720 /* line is guaranteed by OpenSSL to be NUL terminated */
721 rc =
write(
fd, line, strlen(line));
727 (void) rc;
/* silence compiler warnings */
733 * Create per-connection SSL object, and load the client certificate,
734 * private key, and trusted CA certs.
736 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
751 * We'll need the home directory if any of the relevant parameters are
752 * defaulted. If pqGetHomeDirectory fails, act as though none of the
753 * files could be found.
761 else /* won't need it */
762 have_homedir =
false;
765 * Create a new SSL_CTX object.
767 * We used to share a single SSL_CTX between all connections, but it was
768 * complicated if connections used different certificates. So now we
769 * create a separate context for each connection, and accept the overhead.
782 * Delegate the client cert password prompt to the libpq wrapper callback
785 * If the application hasn't installed its own and the sslpassword
786 * parameter is non-null, we install ours now to make sure we supply
787 * PGconn->sslpassword to OpenSSL instead of letting it prompt on stdin.
789 * This will replace OpenSSL's default PEM_def_callback (which prompts on
790 * stdin), but we're only setting it for this SSL context so it's
800#ifdef HAVE_SSL_CTX_SET_CERT_CB
801 /* Set up a certificate selection callback. */
805 /* Disable old protocol versions */
806 SSL_CTX_set_options(
SSL_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
808 /* Set the minimum and maximum protocol versions if necessary */
816 if (ssl_min_ver == -1)
824 if (!SSL_CTX_set_min_proto_version(
SSL_context, ssl_min_ver))
842 if (ssl_max_ver == -1)
850 if (!SSL_CTX_set_max_proto_version(
SSL_context, ssl_max_ver))
862 * Disable OpenSSL's moving-write-buffer sanity check, because it causes
863 * unnecessary failures in nonblocking send cases.
865 SSL_CTX_set_mode(
SSL_context, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
868 * If the root cert file exists, load it so we can perform certificate
869 * verification. If sslmode is "verify-full" we will also do further
870 * verification after the connection has been completed.
874 else if (have_homedir)
875 snprintf(fnbuf,
sizeof(fnbuf),
"%s/%s", homedir, ROOT_CERT_FILE);
879 if (strcmp(fnbuf,
"system") == 0)
882 * The "system" sentinel value indicates that we should load whatever
883 * root certificates are installed for use by OpenSSL; these locations
884 * differ by platform. Note that the default system locations may be
885 * further overridden by the SSL_CERT_DIR and SSL_CERT_FILE
886 * environment variables.
888 if (SSL_CTX_set_default_verify_paths(
SSL_context) != 1)
898 have_rootcert =
true;
900 else if (fnbuf[0] !=
'0円' &&
905 if (SSL_CTX_load_verify_locations(
SSL_context, fnbuf, NULL) != 1)
916 if ((cvstore = SSL_CTX_get_cert_store(
SSL_context)) != NULL)
926 /* defaults to use the default CRL file */
927 if (!fname && !dname && have_homedir)
929 snprintf(fnbuf,
sizeof(fnbuf),
"%s/%s", homedir, ROOT_CRL_FILE);
933 /* Set the flags to check against the complete CRL chain */
934 if ((fname || dname) &&
935 X509_STORE_load_locations(cvstore, fname, dname) == 1)
937 X509_STORE_set_flags(cvstore,
938 X509_V_FLAG_CRL_CHECK | X509_V_FLAG_CRL_CHECK_ALL);
941 /* if not found, silently ignore; we do not require CRL */
944 have_rootcert =
true;
949 * stat() failed; assume root file doesn't exist. If sslmode is
950 * verify-ca or verify-full, this is an error. Otherwise, continue
951 * without performing any server cert verification.
953 if (
conn->
sslmode[0] ==
'v')
/* "verify-ca" or "verify-full" */
956 * The only way to reach here with an empty filename is if
957 * pqGetHomeDirectory failed. That's a sufficiently unusual case
958 * that it seems worth having a specialized error message for it.
960 if (fnbuf[0] ==
'0円')
962 "Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.");
965 "Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.", fnbuf);
969 have_rootcert =
false;
972 /* Read the client certificate file */
975 else if (have_homedir)
976 snprintf(fnbuf,
sizeof(fnbuf),
"%s/%s", homedir, USER_CERT_FILE);
982 /* don't send a client cert even if we have one */
985 else if (fnbuf[0] ==
'0円')
987 /* no home directory, proceed without a client cert */
990 else if (
stat(fnbuf, &
buf) != 0)
993 * If file is not present, just go on without a client cert; server
994 * might or might not accept the connection. Any other error,
995 * however, is grounds for complaint.
997 if (errno != ENOENT && errno != ENOTDIR)
1000 fnbuf,
strerror_r(errno, sebuf,
sizeof(sebuf)));
1009 * Cert file exists, so load it. Since OpenSSL doesn't provide the
1010 * equivalent of "SSL_use_certificate_chain_file", we have to load it
1011 * into the SSL context, rather than the SSL object.
1013 if (SSL_CTX_use_certificate_chain_file(
SSL_context, fnbuf) != 1)
1024 /* need to load the associated private key, too */
1029 * The SSL context is now loaded with the correct root and client
1030 * certificates. Create a connection-specific SSL object. The private key
1031 * is loaded directly into the SSL object. (We could load the private key
1032 * into the context, too, but we have done it this way historically, and
1033 * it doesn't really matter.)
1036 !SSL_set_app_data(
conn->ssl,
conn) ||
1049 * If SSL key logging is requested, set up the callback if a compatible
1050 * version of OpenSSL is used and libpq was compiled to support it.
1054#ifdef HAVE_SSL_CTX_SET_KEYLOG_CALLBACK
1055 SSL_CTX_set_keylog_callback(
SSL_context, SSL_CTX_keylog_cb);
1057#ifdef LIBRESSL_VERSION_NUMBER
1066 * SSL contexts are reference counted by OpenSSL. We can free it as soon
1067 * as we have created the SSL object, and it will stick around for as long
1068 * as it's actually needed.
1074 * Set Server Name Indication (SNI), if enabled by connection parameters.
1075 * Per RFC 6066, do not set it if the host is a literal IP address (IPv4
1082 if (host && host[0] &&
1083 !(strspn(host,
"0123456789.") == strlen(host) ||
1086 if (SSL_set_tlsext_host_name(
conn->ssl, host) != 1)
1114 * Read the SSL key. If a key is specified, treat it as an engine:key
1115 * combination if there is colon present - we don't support files with
1116 * colon in the name. The exception is if the second character is a colon,
1117 * in which case it can be a Windows filename with drive specification.
1121#ifdef USE_SSL_ENGINE
1128 /* Colon, but not in second character, treat as engine:key */
1133 if (engine_str == NULL)
1139 /* cannot return NULL because we already checked before strdup */
1140 engine_colon = strchr(engine_str,
':');
1142 *engine_colon =
'0円';
/* engine_str now has engine name */
1143 engine_colon++;
/* engine_colon now has key name */
1145 conn->engine = ENGINE_by_id(engine_str);
1146 if (
conn->engine == NULL)
1157 if (ENGINE_init(
conn->engine) == 0)
1164 ENGINE_free(
conn->engine);
1165 conn->engine = NULL;
1170 pkey = ENGINE_load_private_key(
conn->engine, engine_colon,
1177 engine_colon, engine_str,
err);
1179 ENGINE_finish(
conn->engine);
1180 ENGINE_free(
conn->engine);
1181 conn->engine = NULL;
1185 if (SSL_use_PrivateKey(
conn->ssl, pkey) != 1)
1190 engine_colon, engine_str,
err);
1192 ENGINE_finish(
conn->engine);
1193 ENGINE_free(
conn->engine);
1194 conn->engine = NULL;
1201 fnbuf[0] =
'0円';
/* indicate we're not going to load from a
1205#endif /* USE_SSL_ENGINE */
1207 /* PGSSLKEY is not an engine, treat it as a filename */
1211 else if (have_homedir)
1213 /* No PGSSLKEY specified, load default file */
1214 snprintf(fnbuf,
sizeof(fnbuf),
"%s/%s", homedir, USER_KEY_FILE);
1219 if (have_cert && fnbuf[0] !=
'0円')
1221 /* read the client key from file */
1225 if (errno == ENOENT)
1234 /* Key file must be a regular file */
1243 * Refuse to load world-readable key files. We accept root-owned
1244 * files with mode 0640 or less, so that we can access system-wide
1245 * certificates if we have a supplementary group membership that
1246 * allows us to read 'em. For files with non-root ownership, require
1247 * mode 0600 or less. We need not check the file's ownership exactly;
1248 * if we're able to read it despite it having such restrictive
1249 * permissions, it must have the right ownership.
1251 * Note: be very careful about tightening these rules. Some people
1252 * expect, for example, that a client process running as root should
1253 * be able to use a non-root-owned key file.
1255 * Note that roughly similar checks are performed in
1256 * src/backend/libpq/be-secure-common.c so any changes here may need
1257 * to be made there as well. However, this code caters for the case
1258 * of current user == root, while that code does not.
1260 * Ideally we would do similar permissions checks on Windows, but it
1261 * is not clear how that would work since Unix-style permissions may
1264#if !defined(WIN32) && !defined(__CYGWIN__)
1265 if (
buf.st_uid == 0 ?
1270 "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",
1276 if (SSL_use_PrivateKey_file(
conn->ssl, fnbuf, SSL_FILETYPE_PEM) != 1)
1281 * We'll try to load the file in DER (binary ASN.1) format, and if
1282 * that fails too, report the original error. This could mask
1283 * issues where there's something wrong with a DER-format cert,
1284 * but we'd have to duplicate openssl's format detection to be
1285 * smarter than this. We can't just probe for a leading -----BEGIN
1286 * because PEM can have leading non-matching lines and blanks.
1287 * OpenSSL doesn't expose its get_name(...) and its PEM routines
1288 * don't differentiate between failure modes in enough detail to
1289 * let us tell the difference between "not PEM, try DER" and
1292 if (SSL_use_PrivateKey_file(
conn->ssl, fnbuf, SSL_FILETYPE_ASN1) != 1)
1304 /* verify that the cert and key go together */
1306 SSL_check_private_key(
conn->ssl) != 1)
1317 * If a root cert was loaded, also set our certificate verification
1324 * Set compression option if necessary.
1327 SSL_set_options(
conn->ssl, SSL_OP_NO_COMPRESSION);
1329 SSL_clear_options(
conn->ssl, SSL_OP_NO_COMPRESSION);
1335 * Attempt to negotiate SSL connection.
1344 r = SSL_connect(
conn->ssl);
1348 int err = SSL_get_error(
conn->ssl, r);
1349 unsigned long ecode;
1351 ecode = ERR_get_error();
1354 case SSL_ERROR_WANT_READ:
1357 case SSL_ERROR_WANT_WRITE:
1360 case SSL_ERROR_SYSCALL:
1363 unsigned long vcode;
1365 vcode = SSL_get_verify_result(
conn->ssl);
1368 * If we get an X509 error here for failing to load the
1369 * local issuer cert, without an error in the socket layer
1370 * it means that verification failed due to a missing
1371 * system CA pool without it being a protocol error. We
1372 * inspect the sslrootcert setting to ensure that the user
1373 * was using the system CA pool. For other errors, log
1374 * them using the normal SYSCALL logging.
1376 if (save_errno == 0 &&
1377 vcode == X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY &&
1380 X509_verify_cert_error_string(vcode));
1381 else if (r == -1 && save_errno != 0)
1395 switch (ERR_GET_REASON(ecode))
1398 * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
1399 * TLSV1_ALERT_PROTOCOL_VERSION have been observed
1400 * when trying to communicate with an old OpenSSL
1401 * library, or when the client and server specify
1402 * disjoint protocol ranges.
1403 * NO_PROTOCOLS_AVAILABLE occurs if there's a
1404 * local misconfiguration (which can happen
1405 * despite our checks, if openssl.cnf injects a
1406 * limit we didn't account for). It's not very
1407 * clear what would make OpenSSL return the other
1408 * codes listed here, but a hint about protocol
1409 * versions seems like it's appropriate for all.
1411 case SSL_R_NO_PROTOCOLS_AVAILABLE:
1412 case SSL_R_UNSUPPORTED_PROTOCOL:
1413 case SSL_R_BAD_PROTOCOL_VERSION_NUMBER:
1414 case SSL_R_UNKNOWN_PROTOCOL:
1415 case SSL_R_UNKNOWN_SSL_VERSION:
1416 case SSL_R_UNSUPPORTED_SSL_VERSION:
1417 case SSL_R_WRONG_SSL_VERSION:
1418 case SSL_R_WRONG_VERSION_NUMBER:
1419 case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION:
1420#ifdef SSL_R_VERSION_TOO_HIGH
1421 case SSL_R_VERSION_TOO_HIGH:
1422 case SSL_R_VERSION_TOO_LOW:
1427 MIN_OPENSSL_TLS_VERSION,
1430 MAX_OPENSSL_TLS_VERSION);
1446 /* ALPN is mandatory with direct SSL connections */
1449 const unsigned char *selected;
1452 SSL_get0_alpn_selected(
conn->ssl, &selected, &
len);
1454 if (selected == NULL)
1462 * We only support one protocol so that's what the negotiation should
1463 * always choose, but doesn't hurt to check.
1475 * We already checked the server certificate in initialize_SSL() using
1476 * SSL_CTX_set_verify(), if root.crt exists.
1479 /* get server certificate */
1480 conn->peer = SSL_get_peer_certificate(
conn->ssl);
1481 if (
conn->peer == NULL)
1497 /* SSL handshake is complete */
1509 * We can't destroy everything SSL-related here due to the
1510 * possible later calls to OpenSSL routines which may need our
1511 * thread callbacks, so set a flag here and check at the end.
1514 SSL_shutdown(
conn->ssl);
1515 SSL_free(
conn->ssl);
1523 X509_free(
conn->peer);
1527#ifdef USE_SSL_ENGINE
1530 ENGINE_finish(
conn->engine);
1531 ENGINE_free(
conn->engine);
1532 conn->engine = NULL;
1540 * Obtain reason string for passed SSL errcode
1542 * ERR_get_error() is used by caller to get errcode to pass here.
1543 * The result must be freed after use, using SSLerrfree.
1545 * Some caution is needed here since ERR_reason_error_string will return NULL
1546 * if it doesn't recognize the error code, or (in OpenSSL >= 3) if the code
1547 * represents a system errno value. We don't want to return NULL ever.
1549 static char ssl_nomem[] =
"out of memory allocating error description";
1551 #define SSL_ERR_LEN 128
1556 const char *errreason;
1567 errreason = ERR_reason_error_string(ecode);
1568 if (errreason != NULL)
1575 * Server aborted the connection with TLS "no_application_protocol" alert.
1576 * The ERR_reason_error_string() function doesn't give any error string
1577 * for that for some reason, so do it ourselves. See
1578 * https://github.com/openssl/openssl/issues/24300. This is available in
1579 * OpenSSL 1.1.0 and later, as well as in LibreSSL 3.4.3 (OpenBSD 7.0) and
1582#ifdef SSL_AD_NO_APPLICATION_PROTOCOL
1583 if (ERR_GET_LIB(ecode) == ERR_LIB_SSL &&
1584 ERR_GET_REASON(ecode) == SSL_AD_REASON_OFFSET + SSL_AD_NO_APPLICATION_PROTOCOL)
1592 * In OpenSSL 3.0.0 and later, ERR_reason_error_string does not map system
1593 * errno values anymore. (See OpenSSL source code for the explanation.)
1594 * We can cover that shortcoming with this bit of code. Older OpenSSL
1595 * versions don't have the ERR_SYSTEM_ERROR macro, but that's okay because
1596 * they don't have the shortcoming either.
1598#ifdef ERR_SYSTEM_ERROR
1599 if (ERR_SYSTEM_ERROR(ecode))
1606 /* No choice but to report the numeric ecode */
1618/* ------------------------------------------------------------ */
1619/* SSL information functions */
1620/* ------------------------------------------------------------ */
1623 * Return pointer to OpenSSL object.
1638 if (strcmp(struct_name,
"OpenSSL") == 0)
1646 static const char *
const openssl_attrs[] = {
1655 static const char *
const empty_attrs[] = {NULL};
1659 /* Return attributes of default SSL library */
1660 return openssl_attrs;
1663 /* No attrs for unencrypted connection */
1664 if (
conn->ssl == NULL)
1667 return openssl_attrs;
1675 /* PQsslAttribute(NULL, "library") reports the default SSL library */
1676 if (strcmp(attribute_name,
"library") == 0)
1681 /* All attributes read as NULL for a non-encrypted connection */
1682 if (
conn->ssl == NULL)
1685 if (strcmp(attribute_name,
"library") == 0)
1688 if (strcmp(attribute_name,
"key_bits") == 0)
1690 static char sslbits_str[12];
1693 SSL_get_cipher_bits(
conn->ssl, &sslbits);
1694 snprintf(sslbits_str,
sizeof(sslbits_str),
"%d", sslbits);
1698 if (strcmp(attribute_name,
"cipher") == 0)
1699 return SSL_get_cipher(
conn->ssl);
1701 if (strcmp(attribute_name,
"compression") == 0)
1702 return SSL_get_current_compression(
conn->ssl) ?
"on" :
"off";
1704 if (strcmp(attribute_name,
"protocol") == 0)
1705 return SSL_get_version(
conn->ssl);
1707 if (strcmp(attribute_name,
"alpn") == 0)
1709 const unsigned char *
data;
1711 static char alpn_str[256];
/* alpn doesn't support longer than 255
1715 if (
data == NULL ||
len == 0 ||
len >
sizeof(alpn_str) - 1)
1722 return NULL;
/* unknown attribute */
1726 * Private substitute BIO: this does the sending and receiving using
1727 * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1728 * functions to disable SIGPIPE and give better error messages on I/O errors.
1730 * These functions are closely modelled on the standard socket BIO in OpenSSL;
1731 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1734/* protected by ssl_config_mutex */
1744 BIO_clear_retry_flags(h);
1748 /* If we were interrupted, tell caller to retry */
1754#if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1758 BIO_set_retry_read(h);
1778 BIO_clear_retry_flags(h);
1781 /* If we were interrupted, tell caller to retry */
1787#if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1791 BIO_set_retry_write(h);
1813 * This should not be needed. pgconn_bio_read already has a way to
1814 * signal EOF to OpenSSL. However, OpenSSL made an undocumented,
1815 * backwards-incompatible change and now expects EOF via BIO_ctrl.
1816 * See https://github.com/openssl/openssl/issues/8208
1820 case BIO_CTRL_FLUSH:
1821 /* libssl expects all BIOs to support BIO_flush. */
1846 my_bio_index = BIO_get_new_index();
1847 if (my_bio_index == -1)
1849 my_bio_index |= BIO_TYPE_SOURCE_SINK;
1850 res = BIO_meth_new(my_bio_index,
"libpq socket");
1855 * As of this writing, these functions never fail. But check anyway,
1856 * like OpenSSL's own examples do.
1881 BIO_METHOD *bio_method;
1884 if (bio_method == NULL)
1887 bio = BIO_new(bio_method);
1891 BIO_set_data(bio,
conn);
1892 BIO_set_init(bio, 1);
1894 SSL_set_bio(
conn->ssl, bio, bio);
1899 * This is the default handler to return a client cert password from
1900 * conn->sslpassword. Apps may install it explicitly if they want to
1901 * prevent openssl from ever prompting on stdin.
1911 buf[size - 1] =
'0円';
1934 * Supply a password to decrypt a client certificate.
1936 * This must match OpenSSL type pem_password_cb.
1950 * Convert TLS protocol version string to OpenSSL values
1952 * If a version is passed that is not supported by the current OpenSSL version,
1953 * then we return -1. If a non-negative value is returned, subsequent code can
1954 * assume it is working with a supported version.
1956 * Note: this is rather similar to the backend routine in be-secure-openssl.c,
1957 * so make sure to update both routines if changing this one.
1963 return TLS1_VERSION;
1965#ifdef TLS1_1_VERSION
1967 return TLS1_1_VERSION;
1970#ifdef TLS1_2_VERSION
1972 return TLS1_2_VERSION;
1975#ifdef TLS1_3_VERSION
1977 return TLS1_3_VERSION;
static SSL_CTX * SSL_context
#define fprintf(file, fmt, msg)
void err(int eval, const char *fmt,...)
bool pqGetHomeDirectory(char *buf, int bufsize)
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 BIO_METHOD * pgconn_bio_method_ptr
static int ssl_protocol_version_to_openssl(const char *protocol)
void * PQgetssl(PGconn *conn)
static void SSLerrfree(char *buf)
PQsslKeyPassHook_OpenSSL_type PQgetSSLKeyPassHook_OpenSSL(void)
void * PQsslStruct(PGconn *conn, const char *struct_name)
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 int pgconn_bio_read(BIO *h, char *buf, int size)
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)
static long pgconn_bio_ctrl(BIO *h, int cmd, long num, void *ptr)
static int pgconn_bio_write(BIO *h, const char *buf, int size)
ssize_t pgtls_write(PGconn *conn, const void *ptr, size_t len)
static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook
char * pgtls_get_peer_certificate_hash(PGconn *conn, size_t *len)
const char * PQsslAttribute(PGconn *conn, const char *attribute_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)
static PostgresPollingStatusType open_client_SSL(PGconn *conn)
static unsigned char alpn_protos[]
static int ssl_set_pgconn_bio(PGconn *conn)
void pgtls_close(PGconn *conn)
const char *const * PQsslAttributeNames(PGconn *conn)
void PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook)
static BIO_METHOD * pgconn_bio_method(void)
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)
Assert(PointerIsAligned(start, uint64))
int(* PQsslKeyPassHook_OpenSSL_type)(char *buf, int size, PGconn *conn)
PostgresPollingStatusType
#define SOCK_ERRNO_SET(e)
void libpq_append_conn_error(PGconn *conn, const char *fmt,...)
#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)
char * ssl_max_protocol_version
char * ssl_min_protocol_version
PQExpBufferData errorMessage
bool ssl_handshake_started