1 /*-------------------------------------------------------------------------
7 * Portions Copyright (c) 1996-2023, 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 *-------------------------------------------------------------------------
23 #include "postgres_fe.h"
31 #include "fe-secure-common.h"
32 #include "libpq-int.h"
37 #include <sys/socket.h>
40 #include <netinet/in.h>
41 #include <netinet/tcp.h>
42 #include <arpa/inet.h>
47 #ifdef ENABLE_THREAD_SAFETY
49 #include "pthread-win32.h"
56 * These SSL-related #includes must come after all system-provided headers.
57 * This ensures that OpenSSL can take care of conflicts with Windows'
58 * <wincrypt.h> by #undef'ing the conflicting macros. (We don't directly
59 * include <wincrypt.h>, but some other Windows headers do.)
61 #include "common/openssl.h"
62 #include <openssl/conf.h>
64 #include <openssl/engine.h>
66 #include <openssl/x509v3.h>
69 static int verify_cb(int ok
, X509_STORE_CTX
*ctx
);
70 static int openssl_verify_peer_name_matches_certificate_name(PGconn
*conn
,
71 ASN1_STRING
*name_entry
,
73 static int openssl_verify_peer_name_matches_certificate_ip(PGconn
*conn
,
74 ASN1_OCTET_STRING
*addr_entry
,
76 static void destroy_ssl_system(void);
77 static int initialize_SSL(PGconn
*conn
);
78 static PostgresPollingStatusType
open_client_SSL(PGconn
*conn
);
79 static char *SSLerrmessage(unsigned long ecode
);
80 static void SSLerrfree(char *buf
);
81 static int PQssl_passwd_cb(char *buf
, int size
, int rwflag
, void *userdata
);
83 static int my_sock_read(BIO
*h
, char *buf
, int size
);
84 static int my_sock_write(BIO
*h
, const char *buf
, int size
);
85 static BIO_METHOD
*my_BIO_s_socket(void);
86 static int my_SSL_set_fd(PGconn
*conn
, int fd
);
89 static bool pq_init_ssl_lib
= true;
90 static bool pq_init_crypto_lib
= true;
92 static bool ssl_lib_initialized
= false;
94 #ifdef ENABLE_THREAD_SAFETY
95 static long crypto_open_connections
= 0;
97 static pthread_mutex_t ssl_config_mutex
= PTHREAD_MUTEX_INITIALIZER
;
98 #endif /* ENABLE_THREAD_SAFETY */
100 static PQsslKeyPassHook_OpenSSL_type PQsslKeyPassHook
= NULL
;
101 static int ssl_protocol_version_to_openssl(const char *protocol
);
103 /* ------------------------------------------------------------ */
104 /* Procedures common to all secure sessions */
105 /* ------------------------------------------------------------ */
108 pgtls_init_library(bool do_ssl
, int do_crypto
)
110 #ifdef ENABLE_THREAD_SAFETY
113 * Disallow changing the flags while we have open connections, else we'd
114 * get completely confused.
116 if (crypto_open_connections
!= 0)
120 pq_init_ssl_lib
= do_ssl
;
121 pq_init_crypto_lib
= do_crypto
;
124 PostgresPollingStatusType
125 pgtls_open_client(PGconn
*conn
)
127 /* First time through? */
128 if (conn
->ssl
== NULL
)
131 * Create a connection-specific SSL object, and load client
132 * certificate, private key, and trusted CA certs.
134 if (initialize_SSL(conn
) != 0)
136 /* initialize_SSL already put a message in conn->errorMessage */
138 return PGRES_POLLING_FAILED
;
142 /* Begin or continue the actual handshake */
143 return open_client_SSL(conn
);
147 pgtls_read(PGconn
*conn
, void *ptr
, size_t len
)
150 int result_errno
= 0;
151 char sebuf
[PG_STRERROR_R_BUFLEN
];
158 * Prepare to call SSL_get_error() by clearing thread's OpenSSL error
159 * queue. In general, the current thread's error queue must be empty
160 * before the TLS/SSL I/O operation is attempted, or SSL_get_error() will
161 * not work reliably. Since the possibility exists that other OpenSSL
162 * clients running in the same thread but not under our control will fail
163 * to call ERR_get_error() themselves (after their own I/O operations),
164 * pro-actively clear the per-thread error queue now.
168 n
= SSL_read(conn
->ssl
, ptr
, len
);
169 err
= SSL_get_error(conn
->ssl
, n
);
172 * Other clients of OpenSSL may fail to call ERR_get_error(), but we
173 * always do, so as to not cause problems for OpenSSL clients that don't
174 * call ERR_clear_error() defensively. Be sure that this happens by
175 * calling now. SSL_get_error() relies on the OpenSSL per-thread error
176 * queue being intact, so this is the earliest possible point
177 * ERR_get_error() may be called.
179 ecode
= (err
!= SSL_ERROR_NONE
|| n
< 0) ? ERR_get_error() : 0;
185 /* Not supposed to happen, so we don't translate the msg */
186 appendPQExpBufferStr(&conn
->errorMessage
,
187 "SSL_read failed but did not provide error information\n");
188 /* assume the connection is broken */
189 result_errno
= ECONNRESET
;
192 case SSL_ERROR_WANT_READ
:
195 case SSL_ERROR_WANT_WRITE
:
198 * Returning 0 here would cause caller to wait for read-ready,
199 * which is not correct since what SSL wants is wait for
200 * write-ready. The former could get us stuck in an infinite
201 * wait, so don't risk it; busy-loop instead.
204 case SSL_ERROR_SYSCALL
:
205 if (n
< 0 && SOCK_ERRNO
!= 0)
207 result_errno
= SOCK_ERRNO
;
208 if (result_errno
== EPIPE
||
209 result_errno
== ECONNRESET
)
210 libpq_append_conn_error(conn
, "server closed the connection unexpectedly\n"
211 "\tThis probably means the server terminated abnormally\n"
212 "\tbefore or while processing the request.");
214 libpq_append_conn_error(conn
, "SSL SYSCALL error: %s",
215 SOCK_STRERROR(result_errno
,
216 sebuf
, sizeof(sebuf
)));
220 libpq_append_conn_error(conn
, "SSL SYSCALL error: EOF detected");
221 /* assume the connection is broken */
222 result_errno
= ECONNRESET
;
228 char *errm
= SSLerrmessage(ecode
);
230 libpq_append_conn_error(conn
, "SSL error: %s", errm
);
232 /* assume the connection is broken */
233 result_errno
= ECONNRESET
;
237 case SSL_ERROR_ZERO_RETURN
:
240 * Per OpenSSL documentation, this error code is only returned for
241 * a clean connection closure, so we should not report it as a
244 libpq_append_conn_error(conn
, "SSL connection has been closed unexpectedly");
245 result_errno
= ECONNRESET
;
249 libpq_append_conn_error(conn
, "unrecognized SSL error code: %d", err
);
250 /* assume the connection is broken */
251 result_errno
= ECONNRESET
;
256 /* ensure we return the intended errno to caller */
257 SOCK_ERRNO_SET(result_errno
);
263 pgtls_read_pending(PGconn
*conn
)
265 return SSL_pending(conn
->ssl
) > 0;
269 pgtls_write(PGconn
*conn
, const void *ptr
, size_t len
)
272 int result_errno
= 0;
273 char sebuf
[PG_STRERROR_R_BUFLEN
];
279 n
= SSL_write(conn
->ssl
, ptr
, len
);
280 err
= SSL_get_error(conn
->ssl
, n
);
281 ecode
= (err
!= SSL_ERROR_NONE
|| n
< 0) ? ERR_get_error() : 0;
287 /* Not supposed to happen, so we don't translate the msg */
288 appendPQExpBufferStr(&conn
->errorMessage
,
289 "SSL_write failed but did not provide error information\n");
290 /* assume the connection is broken */
291 result_errno
= ECONNRESET
;
294 case SSL_ERROR_WANT_READ
:
297 * Returning 0 here causes caller to wait for write-ready, which
298 * is not really the right thing, but it's the best we can do.
302 case SSL_ERROR_WANT_WRITE
:
305 case SSL_ERROR_SYSCALL
:
308 * If errno is still zero then assume it's a read EOF situation,
309 * and report EOF. (This seems possible because SSL_write can
312 if (n
< 0 && SOCK_ERRNO
!= 0)
314 result_errno
= SOCK_ERRNO
;
315 if (result_errno
== EPIPE
|| result_errno
== ECONNRESET
)
316 libpq_append_conn_error(conn
, "server closed the connection unexpectedly\n"
317 "\tThis probably means the server terminated abnormally\n"
318 "\tbefore or while processing the request.");
320 libpq_append_conn_error(conn
, "SSL SYSCALL error: %s",
321 SOCK_STRERROR(result_errno
,
322 sebuf
, sizeof(sebuf
)));
326 libpq_append_conn_error(conn
, "SSL SYSCALL error: EOF detected");
327 /* assume the connection is broken */
328 result_errno
= ECONNRESET
;
334 char *errm
= SSLerrmessage(ecode
);
336 libpq_append_conn_error(conn
, "SSL error: %s", errm
);
338 /* assume the connection is broken */
339 result_errno
= ECONNRESET
;
343 case SSL_ERROR_ZERO_RETURN
:
346 * Per OpenSSL documentation, this error code is only returned for
347 * a clean connection closure, so we should not report it as a
350 libpq_append_conn_error(conn
, "SSL connection has been closed unexpectedly");
351 result_errno
= ECONNRESET
;
355 libpq_append_conn_error(conn
, "unrecognized SSL error code: %d", err
);
356 /* assume the connection is broken */
357 result_errno
= ECONNRESET
;
362 /* ensure we return the intended errno to caller */
363 SOCK_ERRNO_SET(result_errno
);
368 #if defined(HAVE_X509_GET_SIGNATURE_NID) || defined(HAVE_X509_GET_SIGNATURE_INFO)
370 pgtls_get_peer_certificate_hash(PGconn
*conn
, size_t *len
)
373 const EVP_MD
*algo_type
;
374 unsigned char hash
[EVP_MAX_MD_SIZE
]; /* size for SHA-512 */
375 unsigned int hash_size
;
384 peer_cert
= conn
->peer
;
387 * Get the signature algorithm of the certificate to determine the hash
388 * algorithm to use for the result. Prefer X509_get_signature_info(),
389 * introduced in OpenSSL 1.1.1, which can handle RSA-PSS signatures.
391 #if HAVE_X509_GET_SIGNATURE_INFO
392 if (!X509_get_signature_info(peer_cert
, &algo_nid
, NULL
, NULL
, NULL
))
394 if (!OBJ_find_sigid_algs(X509_get_signature_nid(peer_cert
),
398 libpq_append_conn_error(conn
, "could not determine server certificate signature algorithm");
403 * The TLS server's certificate bytes need to be hashed with SHA-256 if
404 * its signature algorithm is MD5 or SHA-1 as per RFC 5929
405 * (https://tools.ietf.org/html/rfc5929#section-4.1). If something else
406 * is used, the same hash as the signature algorithm is used.
412 algo_type
= EVP_sha256();
415 algo_type
= EVP_get_digestbynid(algo_nid
);
416 if (algo_type
== NULL
)
418 libpq_append_conn_error(conn
, "could not find digest for NID %s",
419 OBJ_nid2sn(algo_nid
));
425 if (!X509_digest(peer_cert
, algo_type
, hash
, &hash_size
))
427 libpq_append_conn_error(conn
, "could not generate peer certificate hash");
432 cert_hash
= malloc(hash_size
);
433 if (cert_hash
== NULL
)
435 libpq_append_conn_error(conn
, "out of memory");
438 memcpy(cert_hash
, hash
, hash_size
);
443 #endif /* HAVE_X509_GET_SIGNATURE_NID */
445 /* ------------------------------------------------------------ */
446 /* OpenSSL specific code */
447 /* ------------------------------------------------------------ */
450 * Certificate verification callback
452 * This callback allows us to log intermediate problems during
453 * verification, but there doesn't seem to be a clean way to get
454 * our PGconn * structure. So we can't log anything!
456 * This callback also allows us to override the default acceptance
457 * criteria (e.g., accepting self-signed or expired certs), but
458 * for now we accept the default checks.
461 verify_cb(int ok
, X509_STORE_CTX
*ctx
)
466 #ifdef HAVE_SSL_CTX_SET_CERT_CB
468 * Certificate selection callback
470 * This callback lets us choose the client certificate we send to the server
471 * after seeing its CertificateRequest. We only support sending a single
472 * hard-coded certificate via sslcert, so we don't actually set any certificates
473 * here; we just use it to record whether or not the server has actually asked
474 * for one and whether we have one to send.
477 cert_cb(SSL
*ssl
, void *arg
)
481 conn
->ssl_cert_requested
= true;
483 /* Do we have a certificate loaded to send back? */
484 if (SSL_get_certificate(ssl
))
485 conn
->ssl_cert_sent
= true;
488 * Tell OpenSSL that the callback succeeded; we're not required to
489 * actually make any changes to the SSL handle.
496 * OpenSSL-specific wrapper around
497 * pq_verify_peer_name_matches_certificate_name(), converting the ASN1_STRING
498 * into a plain C string.
501 openssl_verify_peer_name_matches_certificate_name(PGconn
*conn
, ASN1_STRING
*name_entry
,
505 const unsigned char *namedata
;
507 /* Should not happen... */
508 if (name_entry
== NULL
)
510 libpq_append_conn_error(conn
, "SSL certificate's name entry is missing");
515 * GEN_DNS can be only IA5String, equivalent to US ASCII.
517 #ifdef HAVE_ASN1_STRING_GET0_DATA
518 namedata
= ASN1_STRING_get0_data(name_entry
);
520 namedata
= ASN1_STRING_data(name_entry
);
522 len
= ASN1_STRING_length(name_entry
);
524 /* OK to cast from unsigned to plain char, since it's all ASCII. */
525 return pq_verify_peer_name_matches_certificate_name(conn
, (const char *) namedata
, len
, store_name
);
529 * OpenSSL-specific wrapper around
530 * pq_verify_peer_name_matches_certificate_ip(), converting the
531 * ASN1_OCTET_STRING into a plain C string.
534 openssl_verify_peer_name_matches_certificate_ip(PGconn
*conn
,
535 ASN1_OCTET_STRING
*addr_entry
,
539 const unsigned char *addrdata
;
541 /* Should not happen... */
542 if (addr_entry
== NULL
)
544 libpq_append_conn_error(conn
, "SSL certificate's address entry is missing");
549 * GEN_IPADD is an OCTET STRING containing an IP address in network byte
552 #ifdef HAVE_ASN1_STRING_GET0_DATA
553 addrdata
= ASN1_STRING_get0_data(addr_entry
);
555 addrdata
= ASN1_STRING_data(addr_entry
);
557 len
= ASN1_STRING_length(addr_entry
);
559 return pq_verify_peer_name_matches_certificate_ip(conn
, addrdata
, len
, store_name
);
563 is_ip_address(const char *host
)
565 struct in_addr dummy4
;
566 #ifdef HAVE_INET_PTON
567 struct in6_addr dummy6
;
570 return inet_aton(host
, &dummy4
)
571 #ifdef HAVE_INET_PTON
572 || (inet_pton(AF_INET6
, host
, &dummy6
) == 1)
578 * Verify that the server certificate matches the hostname we connected to.
580 * The certificate's Common Name and Subject Alternative Names are considered.
583 pgtls_verify_peer_name_matches_certificate_guts(PGconn
*conn
,
587 STACK_OF(GENERAL_NAME
) * peer_san
;
590 char *host
= conn
->connhost
[conn
->whichhost
].host
;
592 bool check_cn
= true;
594 Assert(host
&& host
[0]); /* should be guaranteed by caller */
597 * We try to match the NSS behavior here, which is a slight departure from
598 * the spec but seems to make more intuitive sense:
600 * If connhost contains a DNS name, and the certificate's SANs contain any
601 * dNSName entries, then we'll ignore the Subject Common Name entirely;
602 * otherwise, we fall back to checking the CN. (This behavior matches the
605 * If connhost contains an IP address, and the SANs contain iPAddress
606 * entries, we again ignore the CN. Otherwise, we allow the CN to match,
607 * EVEN IF there is a dNSName in the SANs. (RFC 6125 prohibits this: "A
608 * client MUST NOT seek a match for a reference identifier of CN-ID if the
609 * presented identifiers include a DNS-ID, SRV-ID, URI-ID, or any
610 * application-specific identifier types supported by the client.")
612 * NOTE: Prior versions of libpq did not consider iPAddress entries at
613 * all, so this new behavior might break a certificate that has different
614 * IP addresses in the Subject CN and the SANs.
616 if (is_ip_address(host
))
617 host_type
= GEN_IPADD
;
622 * First, get the Subject Alternative Names (SANs) from the certificate,
623 * and compare them against the originally given hostname.
625 peer_san
= (STACK_OF(GENERAL_NAME
) *)
626 X509_get_ext_d2i(conn
->peer
, NID_subject_alt_name
, NULL
, NULL
);
630 int san_len
= sk_GENERAL_NAME_num(peer_san
);
632 for (i
= 0; i
< san_len
; i
++)
634 const GENERAL_NAME
*name
= sk_GENERAL_NAME_value(peer_san
, i
);
635 char *alt_name
= NULL
;
637 if (name
->type
== host_type
)
640 * This SAN is of the same type (IP or DNS) as our host name,
641 * so don't allow a fallback check of the CN.
646 if (name
->type
== GEN_DNS
)
649 rc
= openssl_verify_peer_name_matches_certificate_name(conn
,
653 else if (name
->type
== GEN_IPADD
)
656 rc
= openssl_verify_peer_name_matches_certificate_ip(conn
,
664 *first_name
= alt_name
;
672 * Either we hit an error or a match, and either way we should
673 * not fall back to the CN.
679 sk_GENERAL_NAME_pop_free(peer_san
, GENERAL_NAME_free
);
683 * If there is no subjectAltName extension of the matching type, check the
686 * (Per RFC 2818 and RFC 6125, if the subjectAltName extension of type
687 * dNSName is present, the CN must be ignored. We break this rule if host
688 * is an IP address; see the comment above.)
692 X509_NAME
*subject_name
;
694 subject_name
= X509_get_subject_name(conn
->peer
);
695 if (subject_name
!= NULL
)
699 cn_index
= X509_NAME_get_index_by_NID(subject_name
,
703 char *common_name
= NULL
;
706 rc
= openssl_verify_peer_name_matches_certificate_name(conn
,
707 X509_NAME_ENTRY_get_data(X509_NAME_get_entry(subject_name
, cn_index
)),
713 *first_name
= common_name
;
724 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
726 * Callback functions for OpenSSL internal locking. (OpenSSL 1.1.0
727 * does its own locking, and doesn't need these anymore. The
728 * CRYPTO_lock() function was removed in 1.1.0, when the callbacks
729 * were made obsolete, so we assume that if CRYPTO_lock() exists,
730 * the callbacks are still required.)
734 pq_threadidcallback(void)
737 * This is not standards-compliant. pthread_self() returns pthread_t, and
738 * shouldn't be cast to unsigned long, but CRYPTO_set_id_callback requires
739 * it, so we have to do it.
741 return (unsigned long) pthread_self();
744 static pthread_mutex_t
*pq_lockarray
;
747 pq_lockingcallback(int mode
, int n
, const char *file
, int line
)
750 * There's no way to report a mutex-primitive failure, so we just Assert
751 * in development builds, and ignore any errors otherwise. Fortunately
752 * this is all obsolete in modern OpenSSL.
754 if (mode
& CRYPTO_LOCK
)
756 if (pthread_mutex_lock(&pq_lockarray
[n
]))
761 if (pthread_mutex_unlock(&pq_lockarray
[n
]))
765 #endif /* ENABLE_THREAD_SAFETY && HAVE_CRYPTO_LOCK */
768 * Initialize SSL library.
770 * In threadsafe mode, this includes setting up libcrypto callback functions
771 * to do thread locking.
773 * If the caller has told us (through PQinitOpenSSL) that he's taking care
774 * of libcrypto, we expect that callbacks are already set, and won't try to
778 pgtls_init(PGconn
*conn
, bool do_ssl
, bool do_crypto
)
780 #ifdef ENABLE_THREAD_SAFETY
781 if (pthread_mutex_lock(&ssl_config_mutex
))
784 #ifdef HAVE_CRYPTO_LOCK
785 if (pq_init_crypto_lib
)
788 * If necessary, set up an array to hold locks for libcrypto.
789 * libcrypto will tell us how big to make this array.
791 if (pq_lockarray
== NULL
)
795 pq_lockarray
= malloc(sizeof(pthread_mutex_t
) * CRYPTO_num_locks());
798 pthread_mutex_unlock(&ssl_config_mutex
);
801 for (i
= 0; i
< CRYPTO_num_locks(); i
++)
803 if (pthread_mutex_init(&pq_lockarray
[i
], NULL
))
807 pthread_mutex_unlock(&ssl_config_mutex
);
813 if (do_crypto
&& !conn
->crypto_loaded
)
815 if (crypto_open_connections
++ == 0)
818 * These are only required for threaded libcrypto
819 * applications, but make sure we don't stomp on them if
820 * they're already set.
822 if (CRYPTO_get_id_callback() == NULL
)
823 CRYPTO_set_id_callback(pq_threadidcallback
);
824 if (CRYPTO_get_locking_callback() == NULL
)
825 CRYPTO_set_locking_callback(pq_lockingcallback
);
828 conn
->crypto_loaded
= true;
831 #endif /* HAVE_CRYPTO_LOCK */
832 #endif /* ENABLE_THREAD_SAFETY */
834 if (!ssl_lib_initialized
&& do_ssl
)
838 #ifdef HAVE_OPENSSL_INIT_SSL
839 OPENSSL_init_ssl(OPENSSL_INIT_LOAD_CONFIG
, NULL
);
841 OPENSSL_config(NULL
);
843 SSL_load_error_strings();
846 ssl_lib_initialized
= true;
849 #ifdef ENABLE_THREAD_SAFETY
850 pthread_mutex_unlock(&ssl_config_mutex
);
856 * This function is needed because if the libpq library is unloaded
857 * from the application, the callback functions will no longer exist when
858 * libcrypto is used by other parts of the system. For this reason,
859 * we unregister the callback functions when the last libpq
860 * connection is closed. (The same would apply for OpenSSL callbacks
863 * Callbacks are only set when we're compiled in threadsafe mode, so
864 * we only need to remove them in this case. They are also not needed
865 * with OpenSSL 1.1.0 anymore.
868 destroy_ssl_system(void)
870 #if defined(ENABLE_THREAD_SAFETY) && defined(HAVE_CRYPTO_LOCK)
871 if (pthread_mutex_lock(&ssl_config_mutex
))
874 if (pq_init_crypto_lib
&& crypto_open_connections
> 0)
875 --crypto_open_connections
;
877 if (pq_init_crypto_lib
&& crypto_open_connections
== 0)
880 * No connections left, unregister libcrypto callbacks, if no one
881 * registered different ones in the meantime.
883 if (CRYPTO_get_locking_callback() == pq_lockingcallback
)
884 CRYPTO_set_locking_callback(NULL
);
885 if (CRYPTO_get_id_callback() == pq_threadidcallback
)
886 CRYPTO_set_id_callback(NULL
);
889 * We don't free the lock array. If we get another connection in this
890 * process, we will just re-use them with the existing mutexes.
892 * This means we leak a little memory on repeated load/unload of the
897 pthread_mutex_unlock(&ssl_config_mutex
);
902 * Create per-connection SSL object, and load the client certificate,
903 * private key, and trusted CA certs.
905 * Returns 0 if OK, -1 on failure (with a message in conn->errorMessage).
908 initialize_SSL(PGconn
*conn
)
910 SSL_CTX
*SSL_context
;
912 char homedir
[MAXPGPATH
];
913 char fnbuf
[MAXPGPATH
];
914 char sebuf
[PG_STRERROR_R_BUFLEN
];
918 EVP_PKEY
*pkey
= NULL
;
921 * We'll need the home directory if any of the relevant parameters are
922 * defaulted. If pqGetHomeDirectory fails, act as though none of the
923 * files could be found.
925 if (!(conn
->sslcert
&& strlen(conn
->sslcert
) > 0) ||
926 !(conn
->sslkey
&& strlen(conn
->sslkey
) > 0) ||
927 !(conn
->sslrootcert
&& strlen(conn
->sslrootcert
) > 0) ||
928 !((conn
->sslcrl
&& strlen(conn
->sslcrl
) > 0) ||
929 (conn
->sslcrldir
&& strlen(conn
->sslcrldir
) > 0)))
930 have_homedir
= pqGetHomeDirectory(homedir
, sizeof(homedir
));
931 else /* won't need it */
932 have_homedir
= false;
935 * Create a new SSL_CTX object.
937 * We used to share a single SSL_CTX between all connections, but it was
938 * complicated if connections used different certificates. So now we
939 * create a separate context for each connection, and accept the overhead.
941 SSL_context
= SSL_CTX_new(SSLv23_method());
944 char *err
= SSLerrmessage(ERR_get_error());
946 libpq_append_conn_error(conn
, "could not create SSL context: %s", err
);
952 * Delegate the client cert password prompt to the libpq wrapper callback
955 * If the application hasn't installed its own and the sslpassword
956 * parameter is non-null, we install ours now to make sure we supply
957 * PGconn->sslpassword to OpenSSL instead of letting it prompt on stdin.
959 * This will replace OpenSSL's default PEM_def_callback (which prompts on
960 * stdin), but we're only setting it for this SSL context so it's
964 || (conn
->sslpassword
&& strlen(conn
->sslpassword
) > 0))
966 SSL_CTX_set_default_passwd_cb(SSL_context
, PQssl_passwd_cb
);
967 SSL_CTX_set_default_passwd_cb_userdata(SSL_context
, conn
);
970 #ifdef HAVE_SSL_CTX_SET_CERT_CB
971 /* Set up a certificate selection callback. */
972 SSL_CTX_set_cert_cb(SSL_context
, cert_cb
, conn
);
975 /* Disable old protocol versions */
976 SSL_CTX_set_options(SSL_context
, SSL_OP_NO_SSLv2
| SSL_OP_NO_SSLv3
);
978 /* Set the minimum and maximum protocol versions if necessary */
979 if (conn
->ssl_min_protocol_version
&&
980 strlen(conn
->ssl_min_protocol_version
) != 0)
984 ssl_min_ver
= ssl_protocol_version_to_openssl(conn
->ssl_min_protocol_version
);
986 if (ssl_min_ver
== -1)
988 libpq_append_conn_error(conn
, "invalid value \"%s\" for minimum SSL protocol version",
989 conn
->ssl_min_protocol_version
);
990 SSL_CTX_free(SSL_context
);
994 if (!SSL_CTX_set_min_proto_version(SSL_context
, ssl_min_ver
))
996 char *err
= SSLerrmessage(ERR_get_error());
998 libpq_append_conn_error(conn
, "could not set minimum SSL protocol version: %s", err
);
1000 SSL_CTX_free(SSL_context
);
1005 if (conn
->ssl_max_protocol_version
&&
1006 strlen(conn
->ssl_max_protocol_version
) != 0)
1010 ssl_max_ver
= ssl_protocol_version_to_openssl(conn
->ssl_max_protocol_version
);
1012 if (ssl_max_ver
== -1)
1014 libpq_append_conn_error(conn
, "invalid value \"%s\" for maximum SSL protocol version",
1015 conn
->ssl_max_protocol_version
);
1016 SSL_CTX_free(SSL_context
);
1020 if (!SSL_CTX_set_max_proto_version(SSL_context
, ssl_max_ver
))
1022 char *err
= SSLerrmessage(ERR_get_error());
1024 libpq_append_conn_error(conn
, "could not set maximum SSL protocol version: %s", err
);
1026 SSL_CTX_free(SSL_context
);
1032 * Disable OpenSSL's moving-write-buffer sanity check, because it causes
1033 * unnecessary failures in nonblocking send cases.
1035 SSL_CTX_set_mode(SSL_context
, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER
);
1038 * If the root cert file exists, load it so we can perform certificate
1039 * verification. If sslmode is "verify-full" we will also do further
1040 * verification after the connection has been completed.
1042 if (conn
->sslrootcert
&& strlen(conn
->sslrootcert
) > 0)
1043 strlcpy(fnbuf
, conn
->sslrootcert
, sizeof(fnbuf
));
1044 else if (have_homedir
)
1045 snprintf(fnbuf
, sizeof(fnbuf
), "%s/%s", homedir
, ROOT_CERT_FILE
);
1049 if (strcmp(fnbuf
, "system") == 0)
1052 * The "system" sentinel value indicates that we should load whatever
1053 * root certificates are installed for use by OpenSSL; these locations
1054 * differ by platform. Note that the default system locations may be
1055 * further overridden by the SSL_CERT_DIR and SSL_CERT_FILE
1056 * environment variables.
1058 if (SSL_CTX_set_default_verify_paths(SSL_context
) != 1)
1060 char *err
= SSLerrmessage(ERR_get_error());
1062 libpq_append_conn_error(conn
, "could not load system root certificate paths: %s",
1065 SSL_CTX_free(SSL_context
);
1068 have_rootcert
= true;
1070 else if (fnbuf
[0] != '\0' &&
1071 stat(fnbuf
, &buf
) == 0)
1073 X509_STORE
*cvstore
;
1075 if (SSL_CTX_load_verify_locations(SSL_context
, fnbuf
, NULL
) != 1)
1077 char *err
= SSLerrmessage(ERR_get_error());
1079 libpq_append_conn_error(conn
, "could not read root certificate file \"%s\": %s",
1082 SSL_CTX_free(SSL_context
);
1086 if ((cvstore
= SSL_CTX_get_cert_store(SSL_context
)) != NULL
)
1091 if (conn
->sslcrl
&& strlen(conn
->sslcrl
) > 0)
1092 fname
= conn
->sslcrl
;
1093 if (conn
->sslcrldir
&& strlen(conn
->sslcrldir
) > 0)
1094 dname
= conn
->sslcrldir
;
1096 /* defaults to use the default CRL file */
1097 if (!fname
&& !dname
&& have_homedir
)
1099 snprintf(fnbuf
, sizeof(fnbuf
), "%s/%s", homedir
, ROOT_CRL_FILE
);
1103 /* Set the flags to check against the complete CRL chain */
1104 if ((fname
|| dname
) &&
1105 X509_STORE_load_locations(cvstore
, fname
, dname
) == 1)
1107 X509_STORE_set_flags(cvstore
,
1108 X509_V_FLAG_CRL_CHECK
| X509_V_FLAG_CRL_CHECK_ALL
);
1111 /* if not found, silently ignore; we do not require CRL */
1114 have_rootcert
= true;
1119 * stat() failed; assume root file doesn't exist. If sslmode is
1120 * verify-ca or verify-full, this is an error. Otherwise, continue
1121 * without performing any server cert verification.
1123 if (conn
->sslmode
[0] == 'v') /* "verify-ca" or "verify-full" */
1126 * The only way to reach here with an empty filename is if
1127 * pqGetHomeDirectory failed. That's a sufficiently unusual case
1128 * that it seems worth having a specialized error message for it.
1130 if (fnbuf
[0] == '\0')
1131 libpq_append_conn_error(conn
, "could not get home directory to locate root certificate file\n"
1132 "Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.");
1134 libpq_append_conn_error(conn
, "root certificate file \"%s\" does not exist\n"
1135 "Either provide the file, use the system's trusted roots with sslrootcert=system, or change sslmode to disable server certificate verification.", fnbuf
);
1136 SSL_CTX_free(SSL_context
);
1139 have_rootcert
= false;
1142 /* Read the client certificate file */
1143 if (conn
->sslcert
&& strlen(conn
->sslcert
) > 0)
1144 strlcpy(fnbuf
, conn
->sslcert
, sizeof(fnbuf
));
1145 else if (have_homedir
)
1146 snprintf(fnbuf
, sizeof(fnbuf
), "%s/%s", homedir
, USER_CERT_FILE
);
1150 if (conn
->sslcertmode
[0] == 'd') /* disable */
1152 /* don't send a client cert even if we have one */
1155 else if (fnbuf
[0] == '\0')
1157 /* no home directory, proceed without a client cert */
1160 else if (stat(fnbuf
, &buf
) != 0)
1163 * If file is not present, just go on without a client cert; server
1164 * might or might not accept the connection. Any other error,
1165 * however, is grounds for complaint.
1167 if (errno
!= ENOENT
&& errno
!= ENOTDIR
)
1169 libpq_append_conn_error(conn
, "could not open certificate file \"%s\": %s",
1170 fnbuf
, strerror_r(errno
, sebuf
, sizeof(sebuf
)));
1171 SSL_CTX_free(SSL_context
);
1179 * Cert file exists, so load it. Since OpenSSL doesn't provide the
1180 * equivalent of "SSL_use_certificate_chain_file", we have to load it
1181 * into the SSL context, rather than the SSL object.
1183 if (SSL_CTX_use_certificate_chain_file(SSL_context
, fnbuf
) != 1)
1185 char *err
= SSLerrmessage(ERR_get_error());
1187 libpq_append_conn_error(conn
, "could not read certificate file \"%s\": %s",
1190 SSL_CTX_free(SSL_context
);
1194 /* need to load the associated private key, too */
1199 * The SSL context is now loaded with the correct root and client
1200 * certificates. Create a connection-specific SSL object. The private key
1201 * is loaded directly into the SSL object. (We could load the private key
1202 * into the context, too, but we have done it this way historically, and
1203 * it doesn't really matter.)
1205 if (!(conn
->ssl
= SSL_new(SSL_context
)) ||
1206 !SSL_set_app_data(conn
->ssl
, conn
) ||
1207 !my_SSL_set_fd(conn
, conn
->sock
))
1209 char *err
= SSLerrmessage(ERR_get_error());
1211 libpq_append_conn_error(conn
, "could not establish SSL connection: %s", err
);
1213 SSL_CTX_free(SSL_context
);
1216 conn
->ssl_in_use
= true;
1219 * SSL contexts are reference counted by OpenSSL. We can free it as soon
1220 * as we have created the SSL object, and it will stick around for as long
1221 * as it's actually needed.
1223 SSL_CTX_free(SSL_context
);
1227 * Set Server Name Indication (SNI), if enabled by connection parameters.
1228 * Per RFC 6066, do not set it if the host is a literal IP address (IPv4
1231 if (conn
->sslsni
&& conn
->sslsni
[0] == '1')
1233 const char *host
= conn
->connhost
[conn
->whichhost
].host
;
1235 if (host
&& host
[0] &&
1236 !(strspn(host
, "0123456789.") == strlen(host
) ||
1239 if (SSL_set_tlsext_host_name(conn
->ssl
, host
) != 1)
1241 char *err
= SSLerrmessage(ERR_get_error());
1243 libpq_append_conn_error(conn
, "could not set SSL Server Name Indication (SNI): %s", err
);
1251 * Read the SSL key. If a key is specified, treat it as an engine:key
1252 * combination if there is colon present - we don't support files with
1253 * colon in the name. The exception is if the second character is a colon,
1254 * in which case it can be a Windows filename with drive specification.
1256 if (have_cert
&& conn
->sslkey
&& strlen(conn
->sslkey
) > 0)
1258 #ifdef USE_SSL_ENGINE
1259 if (strchr(conn
->sslkey
, ':')
1261 && conn
->sslkey
[1] != ':'
1265 /* Colon, but not in second character, treat as engine:key */
1266 char *engine_str
= strdup(conn
->sslkey
);
1269 if (engine_str
== NULL
)
1271 libpq_append_conn_error(conn
, "out of memory");
1275 /* cannot return NULL because we already checked before strdup */
1276 engine_colon
= strchr(engine_str
, ':');
1278 *engine_colon
= '\0'; /* engine_str now has engine name */
1279 engine_colon
++; /* engine_colon now has key name */
1281 conn
->engine
= ENGINE_by_id(engine_str
);
1282 if (conn
->engine
== NULL
)
1284 char *err
= SSLerrmessage(ERR_get_error());
1286 libpq_append_conn_error(conn
, "could not load SSL engine \"%s\": %s",
1293 if (ENGINE_init(conn
->engine
) == 0)
1295 char *err
= SSLerrmessage(ERR_get_error());
1297 libpq_append_conn_error(conn
, "could not initialize SSL engine \"%s\": %s",
1300 ENGINE_free(conn
->engine
);
1301 conn
->engine
= NULL
;
1306 pkey
= ENGINE_load_private_key(conn
->engine
, engine_colon
,
1310 char *err
= SSLerrmessage(ERR_get_error());
1312 libpq_append_conn_error(conn
, "could not read private SSL key \"%s\" from engine \"%s\": %s",
1313 engine_colon
, engine_str
, err
);
1315 ENGINE_finish(conn
->engine
);
1316 ENGINE_free(conn
->engine
);
1317 conn
->engine
= NULL
;
1321 if (SSL_use_PrivateKey(conn
->ssl
, pkey
) != 1)
1323 char *err
= SSLerrmessage(ERR_get_error());
1325 libpq_append_conn_error(conn
, "could not load private SSL key \"%s\" from engine \"%s\": %s",
1326 engine_colon
, engine_str
, err
);
1328 ENGINE_finish(conn
->engine
);
1329 ENGINE_free(conn
->engine
);
1330 conn
->engine
= NULL
;
1337 fnbuf
[0] = '\0'; /* indicate we're not going to load from a
1341 #endif /* USE_SSL_ENGINE */
1343 /* PGSSLKEY is not an engine, treat it as a filename */
1344 strlcpy(fnbuf
, conn
->sslkey
, sizeof(fnbuf
));
1347 else if (have_homedir
)
1349 /* No PGSSLKEY specified, load default file */
1350 snprintf(fnbuf
, sizeof(fnbuf
), "%s/%s", homedir
, USER_KEY_FILE
);
1355 if (have_cert
&& fnbuf
[0] != '\0')
1357 /* read the client key from file */
1359 if (stat(fnbuf
, &buf
) != 0)
1361 if (errno
== ENOENT
)
1362 libpq_append_conn_error(conn
, "certificate present, but not private key file \"%s\"",
1365 libpq_append_conn_error(conn
, "could not stat private key file \"%s\": %m",
1370 /* Key file must be a regular file */
1371 if (!S_ISREG(buf
.st_mode
))
1373 libpq_append_conn_error(conn
, "private key file \"%s\" is not a regular file",
1379 * Refuse to load world-readable key files. We accept root-owned
1380 * files with mode 0640 or less, so that we can access system-wide
1381 * certificates if we have a supplementary group membership that
1382 * allows us to read 'em. For files with non-root ownership, require
1383 * mode 0600 or less. We need not check the file's ownership exactly;
1384 * if we're able to read it despite it having such restrictive
1385 * permissions, it must have the right ownership.
1387 * Note: be very careful about tightening these rules. Some people
1388 * expect, for example, that a client process running as root should
1389 * be able to use a non-root-owned key file.
1391 * Note that roughly similar checks are performed in
1392 * src/backend/libpq/be-secure-common.c so any changes here may need
1393 * to be made there as well. However, this code caters for the case
1394 * of current user == root, while that code does not.
1396 * Ideally we would do similar permissions checks on Windows, but it
1397 * is not clear how that would work since Unix-style permissions may
1400 #if !defined(WIN32) && !defined(__CYGWIN__)
1401 if (buf
.st_uid
== 0 ?
1402 buf
.st_mode
& (S_IWGRP
| S_IXGRP
| S_IRWXO
) :
1403 buf
.st_mode
& (S_IRWXG
| S_IRWXO
))
1405 libpq_append_conn_error(conn
,
1406 "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",
1412 if (SSL_use_PrivateKey_file(conn
->ssl
, fnbuf
, SSL_FILETYPE_PEM
) != 1)
1414 char *err
= SSLerrmessage(ERR_get_error());
1417 * We'll try to load the file in DER (binary ASN.1) format, and if
1418 * that fails too, report the original error. This could mask
1419 * issues where there's something wrong with a DER-format cert,
1420 * but we'd have to duplicate openssl's format detection to be
1421 * smarter than this. We can't just probe for a leading -----BEGIN
1422 * because PEM can have leading non-matching lines and blanks.
1423 * OpenSSL doesn't expose its get_name(...) and its PEM routines
1424 * don't differentiate between failure modes in enough detail to
1425 * let us tell the difference between "not PEM, try DER" and
1428 if (SSL_use_PrivateKey_file(conn
->ssl
, fnbuf
, SSL_FILETYPE_ASN1
) != 1)
1430 libpq_append_conn_error(conn
, "could not load private key file \"%s\": %s",
1440 /* verify that the cert and key go together */
1442 SSL_check_private_key(conn
->ssl
) != 1)
1444 char *err
= SSLerrmessage(ERR_get_error());
1446 libpq_append_conn_error(conn
, "certificate does not match private key file \"%s\": %s",
1453 * If a root cert was loaded, also set our certificate verification
1457 SSL_set_verify(conn
->ssl
, SSL_VERIFY_PEER
, verify_cb
);
1460 * Set compression option if necessary.
1462 if (conn
->sslcompression
&& conn
->sslcompression
[0] == '0')
1463 SSL_set_options(conn
->ssl
, SSL_OP_NO_COMPRESSION
);
1465 SSL_clear_options(conn
->ssl
, SSL_OP_NO_COMPRESSION
);
1471 * Attempt to negotiate SSL connection.
1473 static PostgresPollingStatusType
1474 open_client_SSL(PGconn
*conn
)
1480 r
= SSL_connect(conn
->ssl
);
1483 int save_errno
= SOCK_ERRNO
;
1484 int err
= SSL_get_error(conn
->ssl
, r
);
1485 unsigned long ecode
;
1487 ecode
= ERR_get_error();
1490 case SSL_ERROR_WANT_READ
:
1491 return PGRES_POLLING_READING
;
1493 case SSL_ERROR_WANT_WRITE
:
1494 return PGRES_POLLING_WRITING
;
1496 case SSL_ERROR_SYSCALL
:
1498 char sebuf
[PG_STRERROR_R_BUFLEN
];
1499 unsigned long vcode
;
1501 vcode
= SSL_get_verify_result(conn
->ssl
);
1504 * If we get an X509 error here for failing to load the
1505 * local issuer cert, without an error in the socket layer
1506 * it means that verification failed due to a missing
1507 * system CA pool without it being a protocol error. We
1508 * inspect the sslrootcert setting to ensure that the user
1509 * was using the system CA pool. For other errors, log
1510 * them using the normal SYSCALL logging.
1512 if (save_errno
== 0 &&
1513 vcode
== X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY
&&
1514 strcmp(conn
->sslrootcert
, "system") == 0)
1515 libpq_append_conn_error(conn
, "SSL error: certificate verify failed: %s",
1516 X509_verify_cert_error_string(vcode
));
1517 else if (r
== -1 && save_errno
!= 0)
1518 libpq_append_conn_error(conn
, "SSL SYSCALL error: %s",
1519 SOCK_STRERROR(save_errno
, sebuf
, sizeof(sebuf
)));
1521 libpq_append_conn_error(conn
, "SSL SYSCALL error: EOF detected");
1523 return PGRES_POLLING_FAILED
;
1527 char *err
= SSLerrmessage(ecode
);
1529 libpq_append_conn_error(conn
, "SSL error: %s", err
);
1531 switch (ERR_GET_REASON(ecode
))
1534 * UNSUPPORTED_PROTOCOL, WRONG_VERSION_NUMBER, and
1535 * TLSV1_ALERT_PROTOCOL_VERSION have been observed
1536 * when trying to communicate with an old OpenSSL
1537 * library, or when the client and server specify
1538 * disjoint protocol ranges.
1539 * NO_PROTOCOLS_AVAILABLE occurs if there's a
1540 * local misconfiguration (which can happen
1541 * despite our checks, if openssl.cnf injects a
1542 * limit we didn't account for). It's not very
1543 * clear what would make OpenSSL return the other
1544 * codes listed here, but a hint about protocol
1545 * versions seems like it's appropriate for all.
1547 case SSL_R_NO_PROTOCOLS_AVAILABLE
:
1548 case SSL_R_UNSUPPORTED_PROTOCOL
:
1549 case SSL_R_BAD_PROTOCOL_VERSION_NUMBER
:
1550 case SSL_R_UNKNOWN_PROTOCOL
:
1551 case SSL_R_UNKNOWN_SSL_VERSION
:
1552 case SSL_R_UNSUPPORTED_SSL_VERSION
:
1553 case SSL_R_WRONG_SSL_VERSION
:
1554 case SSL_R_WRONG_VERSION_NUMBER
:
1555 case SSL_R_TLSV1_ALERT_PROTOCOL_VERSION
:
1556 #ifdef SSL_R_VERSION_TOO_HIGH
1557 case SSL_R_VERSION_TOO_HIGH
:
1558 case SSL_R_VERSION_TOO_LOW
:
1560 libpq_append_conn_error(conn
, "This may indicate that the server does not support any SSL protocol version between %s and %s.",
1561 conn
->ssl_min_protocol_version
?
1562 conn
->ssl_min_protocol_version
:
1563 MIN_OPENSSL_TLS_VERSION
,
1564 conn
->ssl_max_protocol_version
?
1565 conn
->ssl_max_protocol_version
:
1566 MAX_OPENSSL_TLS_VERSION
);
1572 return PGRES_POLLING_FAILED
;
1576 libpq_append_conn_error(conn
, "unrecognized SSL error code: %d", err
);
1578 return PGRES_POLLING_FAILED
;
1583 * We already checked the server certificate in initialize_SSL() using
1584 * SSL_CTX_set_verify(), if root.crt exists.
1587 /* get server certificate */
1588 conn
->peer
= SSL_get_peer_certificate(conn
->ssl
);
1589 if (conn
->peer
== NULL
)
1591 char *err
= SSLerrmessage(ERR_get_error());
1593 libpq_append_conn_error(conn
, "certificate could not be obtained: %s", err
);
1596 return PGRES_POLLING_FAILED
;
1599 if (!pq_verify_peer_name_matches_certificate(conn
))
1602 return PGRES_POLLING_FAILED
;
1605 /* SSL handshake is complete */
1606 return PGRES_POLLING_OK
;
1610 pgtls_close(PGconn
*conn
)
1612 bool destroy_needed
= false;
1614 if (conn
->ssl_in_use
)
1619 * We can't destroy everything SSL-related here due to the
1620 * possible later calls to OpenSSL routines which may need our
1621 * thread callbacks, so set a flag here and check at the end.
1624 SSL_shutdown(conn
->ssl
);
1625 SSL_free(conn
->ssl
);
1627 conn
->ssl_in_use
= false;
1629 destroy_needed
= true;
1634 X509_free(conn
->peer
);
1638 #ifdef USE_SSL_ENGINE
1641 ENGINE_finish(conn
->engine
);
1642 ENGINE_free(conn
->engine
);
1643 conn
->engine
= NULL
;
1650 * In the non-SSL case, just remove the crypto callbacks if the
1651 * connection has then loaded. This code path has no dependency on
1652 * any pending SSL calls.
1654 if (conn
->crypto_loaded
)
1655 destroy_needed
= true;
1659 * This will remove our crypto locking hooks if this is the last
1660 * connection using libcrypto which means we must wait to call it until
1661 * after all the potential SSL calls have been made, otherwise we can end
1662 * up with a race condition and possible deadlocks.
1664 * See comments above destroy_ssl_system().
1668 destroy_ssl_system();
1669 conn
->crypto_loaded
= false;
1675 * Obtain reason string for passed SSL errcode
1677 * ERR_get_error() is used by caller to get errcode to pass here.
1679 * Some caution is needed here since ERR_reason_error_string will
1680 * return NULL if it doesn't recognize the error code. We don't
1681 * want to return NULL ever.
1683 static char ssl_nomem
[] = "out of memory allocating error description";
1685 #define SSL_ERR_LEN 128
1688 SSLerrmessage(unsigned long ecode
)
1690 const char *errreason
;
1693 errbuf
= malloc(SSL_ERR_LEN
);
1698 snprintf(errbuf
, SSL_ERR_LEN
, libpq_gettext("no SSL error reported"));
1701 errreason
= ERR_reason_error_string(ecode
);
1702 if (errreason
!= NULL
)
1704 strlcpy(errbuf
, errreason
, SSL_ERR_LEN
);
1707 snprintf(errbuf
, SSL_ERR_LEN
, libpq_gettext("SSL error code %lu"), ecode
);
1712 SSLerrfree(char *buf
)
1714 if (buf
!= ssl_nomem
)
1718 /* ------------------------------------------------------------ */
1719 /* SSL information functions */
1720 /* ------------------------------------------------------------ */
1723 * Return pointer to OpenSSL object.
1726 PQgetssl(PGconn
*conn
)
1734 PQsslStruct(PGconn
*conn
, const char *struct_name
)
1738 if (strcmp(struct_name
, "OpenSSL") == 0)
1744 PQsslAttributeNames(PGconn
*conn
)
1746 static const char *const openssl_attrs
[] = {
1754 static const char *const empty_attrs
[] = {NULL
};
1758 /* Return attributes of default SSL library */
1759 return openssl_attrs
;
1762 /* No attrs for unencrypted connection */
1763 if (conn
->ssl
== NULL
)
1766 return openssl_attrs
;
1770 PQsslAttribute(PGconn
*conn
, const char *attribute_name
)
1774 /* PQsslAttribute(NULL, "library") reports the default SSL library */
1775 if (strcmp(attribute_name
, "library") == 0)
1780 /* All attributes read as NULL for a non-encrypted connection */
1781 if (conn
->ssl
== NULL
)
1784 if (strcmp(attribute_name
, "library") == 0)
1787 if (strcmp(attribute_name
, "key_bits") == 0)
1789 static char sslbits_str
[12];
1792 SSL_get_cipher_bits(conn
->ssl
, &sslbits
);
1793 snprintf(sslbits_str
, sizeof(sslbits_str
), "%d", sslbits
);
1797 if (strcmp(attribute_name
, "cipher") == 0)
1798 return SSL_get_cipher(conn
->ssl
);
1800 if (strcmp(attribute_name
, "compression") == 0)
1801 return SSL_get_current_compression(conn
->ssl
) ? "on" : "off";
1803 if (strcmp(attribute_name
, "protocol") == 0)
1804 return SSL_get_version(conn
->ssl
);
1806 return NULL
; /* unknown attribute */
1810 * Private substitute BIO: this does the sending and receiving using
1811 * pqsecure_raw_write() and pqsecure_raw_read() instead, to allow those
1812 * functions to disable SIGPIPE and give better error messages on I/O errors.
1814 * These functions are closely modelled on the standard socket BIO in OpenSSL;
1815 * see sock_read() and sock_write() in OpenSSL's crypto/bio/bss_sock.c.
1816 * XXX OpenSSL 1.0.1e considers many more errcodes than just EINTR as reasons
1817 * to retry; do we need to adopt their logic for that?
1820 /* protected by ssl_config_mutex */
1821 static BIO_METHOD
*my_bio_methods
;
1824 my_sock_read(BIO
*h
, char *buf
, int size
)
1828 res
= pqsecure_raw_read((PGconn
*) BIO_get_app_data(h
), buf
, size
);
1829 BIO_clear_retry_flags(h
);
1832 /* If we were interrupted, tell caller to retry */
1838 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1842 BIO_set_retry_read(h
);
1854 my_sock_write(BIO
*h
, const char *buf
, int size
)
1858 res
= pqsecure_raw_write((PGconn
*) BIO_get_app_data(h
), buf
, size
);
1859 BIO_clear_retry_flags(h
);
1862 /* If we were interrupted, tell caller to retry */
1868 #if defined(EWOULDBLOCK) && (!defined(EAGAIN) || (EWOULDBLOCK != EAGAIN))
1872 BIO_set_retry_write(h
);
1884 my_BIO_s_socket(void)
1888 #ifdef ENABLE_THREAD_SAFETY
1889 if (pthread_mutex_lock(&ssl_config_mutex
))
1893 res
= my_bio_methods
;
1895 if (!my_bio_methods
)
1897 BIO_METHOD
*biom
= (BIO_METHOD
*) BIO_s_socket();
1898 #ifdef HAVE_BIO_METH_NEW
1901 my_bio_index
= BIO_get_new_index();
1902 if (my_bio_index
== -1)
1904 my_bio_index
|= (BIO_TYPE_DESCRIPTOR
| BIO_TYPE_SOURCE_SINK
);
1905 res
= BIO_meth_new(my_bio_index
, "libpq socket");
1910 * As of this writing, these functions never fail. But check anyway,
1911 * like OpenSSL's own examples do.
1913 if (!BIO_meth_set_write(res
, my_sock_write
) ||
1914 !BIO_meth_set_read(res
, my_sock_read
) ||
1915 !BIO_meth_set_gets(res
, BIO_meth_get_gets(biom
)) ||
1916 !BIO_meth_set_puts(res
, BIO_meth_get_puts(biom
)) ||
1917 !BIO_meth_set_ctrl(res
, BIO_meth_get_ctrl(biom
)) ||
1918 !BIO_meth_set_create(res
, BIO_meth_get_create(biom
)) ||
1919 !BIO_meth_set_destroy(res
, BIO_meth_get_destroy(biom
)) ||
1920 !BIO_meth_set_callback_ctrl(res
, BIO_meth_get_callback_ctrl(biom
)))
1925 res
= malloc(sizeof(BIO_METHOD
));
1928 memcpy(res
, biom
, sizeof(BIO_METHOD
));
1929 res
->bread
= my_sock_read
;
1930 res
->bwrite
= my_sock_write
;
1934 my_bio_methods
= res
;
1936 #ifdef ENABLE_THREAD_SAFETY
1937 pthread_mutex_unlock(&ssl_config_mutex
);
1943 #ifdef HAVE_BIO_METH_NEW
1951 #ifdef ENABLE_THREAD_SAFETY
1952 pthread_mutex_unlock(&ssl_config_mutex
);
1957 /* This should exactly match OpenSSL's SSL_set_fd except for using my BIO */
1959 my_SSL_set_fd(PGconn
*conn
, int fd
)
1963 BIO_METHOD
*bio_method
;
1965 bio_method
= my_BIO_s_socket();
1966 if (bio_method
== NULL
)
1968 SSLerr(SSL_F_SSL_SET_FD
, ERR_R_BUF_LIB
);
1971 bio
= BIO_new(bio_method
);
1974 SSLerr(SSL_F_SSL_SET_FD
, ERR_R_BUF_LIB
);
1977 BIO_set_app_data(bio
, conn
);
1979 SSL_set_bio(conn
->ssl
, bio
, bio
);
1980 BIO_set_fd(bio
, fd
, BIO_NOCLOSE
);
1987 * This is the default handler to return a client cert password from
1988 * conn->sslpassword. Apps may install it explicitly if they want to
1989 * prevent openssl from ever prompting on stdin.
1992 PQdefaultSSLKeyPassHook_OpenSSL(char *buf
, int size
, PGconn
*conn
)
1994 if (conn
&& conn
->sslpassword
)
1996 if (strlen(conn
->sslpassword
) + 1 > size
)
1997 fprintf(stderr
, libpq_gettext("WARNING: sslpassword truncated\n"));
1998 strncpy(buf
, conn
->sslpassword
, size
);
1999 buf
[size
- 1] = '\0';
2009 PQsslKeyPassHook_OpenSSL_type
2010 PQgetSSLKeyPassHook_OpenSSL(void)
2012 return PQsslKeyPassHook
;
2016 PQsetSSLKeyPassHook_OpenSSL(PQsslKeyPassHook_OpenSSL_type hook
)
2018 PQsslKeyPassHook
= hook
;
2022 * Supply a password to decrypt a client certificate.
2024 * This must match OpenSSL type pem_password_cb.
2027 PQssl_passwd_cb(char *buf
, int size
, int rwflag
, void *userdata
)
2029 PGconn
*conn
= userdata
;
2031 if (PQsslKeyPassHook
)
2032 return PQsslKeyPassHook(buf
, size
, conn
);
2034 return PQdefaultSSLKeyPassHook_OpenSSL(buf
, size
, conn
);
2038 * Convert TLS protocol version string to OpenSSL values
2040 * If a version is passed that is not supported by the current OpenSSL version,
2041 * then we return -1. If a non-negative value is returned, subsequent code can
2042 * assume it is working with a supported version.
2044 * Note: this is rather similar to the backend routine in be-secure-openssl.c,
2045 * so make sure to update both routines if changing this one.
2048 ssl_protocol_version_to_openssl(const char *protocol
)
2050 if (pg_strcasecmp("TLSv1", protocol
) == 0)
2051 return TLS1_VERSION
;
2053 #ifdef TLS1_1_VERSION
2054 if (pg_strcasecmp("TLSv1.1", protocol
) == 0)
2055 return TLS1_1_VERSION
;
2058 #ifdef TLS1_2_VERSION
2059 if (pg_strcasecmp("TLSv1.2", protocol
) == 0)
2060 return TLS1_2_VERSION
;
2063 #ifdef TLS1_3_VERSION
2064 if (pg_strcasecmp("TLSv1.3", protocol
) == 0)
2065 return TLS1_3_VERSION
;