diff --git a/ext/openssl/extconf.rb b/ext/openssl/extconf.rb
index 398866c80..937741124 100644
--- a/ext/openssl/extconf.rb
+++ b/ext/openssl/extconf.rb
@@ -45,6 +45,8 @@
have_func("rb_io_maybe_wait(0, Qnil, Qnil, Qnil)", "ruby/io.h")
# Ruby 3.2
have_func("rb_io_timeout", "ruby/io.h")
+# Ruby 3.3
+have_func("rb_io_closed_p(Qnil)", "ruby/io.h")
Logging::message "=== Checking for system dependent stuff... ===\n"
have_library("nsl", "t_open")
diff --git a/ext/openssl/ossl_ssl.c b/ext/openssl/ossl_ssl.c
index 51a077d90..ebeccb954 100644
--- a/ext/openssl/ossl_ssl.c
+++ b/ext/openssl/ossl_ssl.c
@@ -36,7 +36,8 @@ VALUE cSSLSocket;
static VALUE eSSLErrorWaitReadable;
static VALUE eSSLErrorWaitWritable;
-static ID id_call, id_npn_protocols_encoded, id_each, id_original_context;
+static ID id_call, id_npn_protocols_encoded, id_each, id_original_context,
+ id_io, id_read_nonblock, id_write_nonblock, id_bio_rbuf, id_bio_wbuf;
static VALUE sym_wait_readable, sym_wait_writable;
static ID id_i_cert_store, id_i_ca_file, id_i_ca_path, id_i_verify_mode,
@@ -47,11 +48,14 @@ static ID id_i_cert_store, id_i_ca_file, id_i_ca_path, id_i_verify_mode,
id_i_session_remove_cb, id_i_npn_select_cb, id_i_npn_protocols,
id_i_alpn_select_cb, id_i_alpn_protocols, id_i_servername_cb,
id_i_verify_hostname, id_i_keylog_cb, id_i_tmp_dh_callback;
-static ID id_i_io, id_i_context, id_i_hostname, id_i_sync_close;
+static ID id_i_context, id_i_hostname, id_i_sync_close;
static int ossl_ssl_ex_ptr_idx;
static int ossl_sslctx_ex_ptr_idx;
+static BIO_METHOD *ossl_ssl_bio_meth;
+static VALUE nonblock_kwargs;
+
static void
ossl_sslctx_mark(void *ptr)
{
@@ -110,8 +114,10 @@ ossl_sslctx_s_alloc(VALUE klass)
return obj;
}
+static void ssl_unset_fd_if_closed(const SSL *ssl);
+
static int
-ssl_cb_call(VALUE (*func)(VALUE args), VALUE args, VALUE *ret)
+ssl_cb_call(const SSL *ssl, VALUE (*func)(VALUE args), VALUE args, VALUE *ret)
{
struct ossl_err_state es;
int state;
@@ -122,6 +128,7 @@ ssl_cb_call(VALUE (*func)(VALUE args), VALUE args, VALUE *ret)
}
ossl_err_state_save(&es);
*ret = rb_protect(func, args, &state);
+ ssl_unset_fd_if_closed(ssl);
ossl_err_state_restore(&es);
if (state) {
ossl_cb_state_set(state);
@@ -183,7 +190,7 @@ ossl_client_cert_cb(SSL *ssl, X509 **x509, EVP_PKEY **pkey)
struct client_cert_cb_args args = { ssl, x509, pkey };
VALUE ret;
- if (!ssl_cb_call(ossl_call_client_cert_cb, (VALUE)&args, &ret))
+ if (!ssl_cb_call(ssl, ossl_call_client_cert_cb, (VALUE)&args, &ret))
return -1;
return RTEST(ret);
}
@@ -224,7 +231,7 @@ ossl_tmp_dh_callback(SSL *ssl, int is_export, int keylength)
struct tmp_dh_callback_args args = {rb_ssl, is_export, keylength};
VALUE ret;
- if (!ssl_cb_call(ossl_call_tmp_dh_callback, (VALUE)&args, &ret))
+ if (!ssl_cb_call(ssl, ossl_call_tmp_dh_callback, (VALUE)&args, &ret))
return NULL;
return (DH *)ret;
}
@@ -256,6 +263,7 @@ ossl_ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
{
VALUE cb, ssl_obj, sslctx_obj, verify_hostname, ret;
SSL *ssl;
+ int ok;
ssl = X509_STORE_CTX_get_ex_data(ctx, SSL_get_ex_data_X509_STORE_CTX_idx());
ssl_obj = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
@@ -265,7 +273,8 @@ ossl_ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
if (preverify_ok && RTEST(verify_hostname) && !SSL_is_server(ssl) &&
!X509_STORE_CTX_get_error_depth(ctx)) {
- if (!ssl_cb_call(call_verify_certificate_identity, (VALUE)ctx, &ret))
+ if (!ssl_cb_call(ssl, call_verify_certificate_identity, (VALUE)ctx,
+ &ret))
return 0;
if (ret != Qtrue) {
preverify_ok = 0;
@@ -273,7 +282,9 @@ ossl_ssl_verify_callback(int preverify_ok, X509_STORE_CTX *ctx)
}
}
- return ossl_verify_cb_call(cb, preverify_ok, ctx);
+ ok = ossl_verify_cb_call(cb, preverify_ok, ctx);
+ ssl_unset_fd_if_closed(ssl);
+ return ok;
}
struct sess_get_cb_args {
@@ -314,7 +325,7 @@ ossl_sslctx_session_get_cb(SSL *ssl, const unsigned char *buf, int len, int *cop
VALUE ret;
OSSL_Debug("SSL SESSION get callback entered");
- if (!ssl_cb_call(ossl_call_session_get_cb, (VALUE)&args, &ret))
+ if (!ssl_cb_call(ssl, ossl_call_session_get_cb, (VALUE)&args, &ret))
return NULL;
if (!ret)
return NULL;
@@ -355,7 +366,7 @@ ossl_sslctx_session_new_cb(SSL *ssl, SSL_SESSION *sess)
VALUE ret;
OSSL_Debug("SSL SESSION new callback entered");
- (void)ssl_cb_call(ossl_call_session_new_cb, (VALUE)&args, &ret);
+ (void)ssl_cb_call(ssl, ossl_call_session_new_cb, (VALUE)&args, &ret);
/*
* return 0 which means to OpenSSL that the session is still
@@ -407,7 +418,7 @@ ossl_sslctx_keylog_cb(const SSL *ssl, const char *line)
args.ssl_obj = ssl_obj;
args.line = line;
- (void)ssl_cb_call(ossl_call_keylog_cb, (VALUE)&args, &ret);
+ (void)ssl_cb_call(ssl, ossl_call_keylog_cb, (VALUE)&args, &ret);
}
#endif
@@ -506,7 +517,7 @@ ssl_servername_cb(SSL *ssl, int *ad, void *arg)
{
VALUE ret;
- if (!ssl_cb_call(ossl_call_servername_cb, (VALUE)ssl, &ret))
+ if (!ssl_cb_call(ssl, ossl_call_servername_cb, (VALUE)ssl, &ret))
return SSL_TLSEXT_ERR_ALERT_FATAL;
return SSL_TLSEXT_ERR_OK;
@@ -539,7 +550,7 @@ ssl_info_cb(const SSL *ssl, int where, int val)
VALUE ret;
if (where & SSL_CB_HANDSHAKE_START && SSL_is_server(ssl)) {
- (void)ssl_cb_call(call_renegotiation_cb, (VALUE)&args, &ret);
+ (void)ssl_cb_call(ssl, call_renegotiation_cb, (VALUE)&args, &ret);
}
}
@@ -610,7 +621,7 @@ ssl_npn_select_cb_common(SSL *ssl, VALUE cb, const unsigned char **out,
args.in = in;
args.inlen = inlen;
- if (!ssl_cb_call(npn_select_cb_common_i, (VALUE)&args, &selected))
+ if (!ssl_cb_call(ssl, npn_select_cb_common_i, (VALUE)&args, &selected))
return SSL_TLSEXT_ERR_ALERT_FATAL;
*out = (unsigned char *)RSTRING_PTR(selected);
@@ -1780,36 +1791,17 @@ ossl_ssl_s_alloc(VALUE klass)
return TypedData_Wrap_Struct(klass, &ossl_ssl_type, NULL);
}
-static VALUE
-peer_ip_address(VALUE io)
-{
- VALUE remote_address = rb_funcall(io, rb_intern("remote_address"), 0);
-
- return rb_funcall(remote_address, rb_intern("inspect_sockaddr"), 0);
-}
-
-static VALUE
-fallback_peer_ip_address(VALUE self, VALUE exc)
-{
- return rb_str_new_cstr("(null)");
-}
-
-static VALUE
-peeraddr_ip_str(VALUE self)
-{
- VALUE io = rb_attr_get(self, id_i_io);
- return rb_rescue2(peer_ip_address, io, fallback_peer_ip_address, Qnil,
- rb_eSystemCallError, (VALUE)0);
-}
-
/*
* call-seq:
* SSLSocket.new(io) => aSSLSocket
* SSLSocket.new(io, ctx) => aSSLSocket
* SSLSocket.new(io, ctx, sync_close:) => aSSLSocket
*
- * Creates a new SSL socket from _io_ which must be a real IO object (not an
- * IO-like object that responds to read/write).
+ * Creates a new SSL socket from the underlying socket _io_ and the SSLContext
+ * _ctx_.
+ *
+ * _io_ is typically a TCPSocket or Socket from the socket library, but can be
+ * any object that behaves like an IO object. See below for details.
*
* If _ctx_ is provided the SSL Sockets initial params will be taken from
* the context.
@@ -1822,6 +1814,20 @@ peeraddr_ip_str(VALUE self)
*
* This method will freeze the SSLContext if one is provided;
* however, session management is still allowed in the frozen SSLContext.
+ *
+ * == Using an \IO-like object as the underlying socket
+ *
+ * As of version 4.1, _io_ must respond to at least the following methods,
+ * which must behave in the same way as the methods of IO with the same name:
+ *
+ * - write_nonblock(string, exception: false)
+ * - read_nonblock(maxlen, buffer, exception: false)
+ * - wait_readable(timeout)
+ * - wait_writable(timeout)
+ * - close
+ * - closed?
+ *
+ * Future versions may require _io_ to respond to more methods of IO.
*/
static VALUE
ossl_ssl_initialize(int argc, VALUE *argv, VALUE self)
@@ -1852,8 +1858,7 @@ ossl_ssl_initialize(int argc, VALUE *argv, VALUE self)
rb_ivar_set(self, id_original_context, v_ctx);
ossl_sslctx_setup(v_ctx);
- Check_Type(io, T_FILE);
- rb_ivar_set(self, id_i_io, io);
+ rb_ivar_set(self, id_io, io);
ssl = SSL_new(ctx);
if (!ssl)
@@ -1868,6 +1873,19 @@ ossl_ssl_initialize(int argc, VALUE *argv, VALUE self)
return self;
}
+/*
+ * call-seq:
+ * ssl.io -> io
+ * ssl.to_io -> io
+ *
+ * Returns the underlying IO object.
+ */
+static VALUE
+ossl_ssl_get_io(VALUE self)
+{
+ return rb_attr_get(self, id_io);
+}
+
#ifndef HAVE_RB_IO_DESCRIPTOR
static int
io_descriptor_fallback(VALUE io)
@@ -1879,31 +1897,67 @@ io_descriptor_fallback(VALUE io)
#define rb_io_descriptor io_descriptor_fallback
#endif
+static BIO *ossl_ssl_bio_setup(SSL *ssl);
+
static VALUE
ossl_ssl_setup(VALUE self)
{
VALUE io;
SSL *ssl;
- rb_io_t *fptr;
GetSSL(self, ssl);
if (ssl_started(ssl))
return Qtrue;
- io = rb_attr_get(self, id_i_io);
- GetOpenFile(io, fptr);
- rb_io_check_readable(fptr);
- rb_io_check_writable(fptr);
- rb_io_set_nonblock(fptr);
- if (!SSL_set_fd(ssl, TO_SOCKET(rb_io_descriptor(io))))
- ossl_raise(eSSLError, "SSL_set_fd");
+ io = ossl_ssl_get_io(self);
+ if (RB_TYPE_P(io, T_FILE)) {
+ rb_io_t *fptr;
+ GetOpenFile(io, fptr);
+ rb_io_check_readable(fptr);
+ rb_io_check_writable(fptr);
+ rb_io_set_nonblock(fptr);
+ if (!SSL_set_fd(ssl, TO_SOCKET(rb_io_descriptor(io))))
+ ossl_raise(eSSLError, "SSL_set_fd");
+ }
+ else {
+ rb_ivar_set(self, id_bio_rbuf, rb_str_buf_new(0));
+ rb_ivar_set(self, id_bio_wbuf, rb_str_buf_new(0));
+
+ BIO *bio = ossl_ssl_bio_setup(ssl);
+ SSL_set_bio(ssl, bio, bio);
+ }
return Qtrue;
}
+#ifndef HAVE_RB_IO_CLOSED_P
+static VALUE
+rb_io_closed_p(VALUE io)
+{
+ return RFILE(io)->fptr->fd < 0 ? Qtrue : Qfalse;
+}
+#endif
+
+static void
+ssl_unset_fd_if_closed(const SSL *ssl)
+{
+ VALUE self = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
+ VALUE io = ossl_ssl_get_io(self);
+
+ if (!RB_TYPE_P(io, T_FILE))
+ return;
+ if (RTEST(rb_io_closed_p(io))) {
+ BIO *bio = SSL_get_rbio(ssl);
+ BIO_set_fd(bio, -1, BIO_NOCLOSE);
+ }
+}
+
static void
ssl_call_begin(VALUE self)
{
+ VALUE io = ossl_ssl_get_io(self);
+ if (RB_TYPE_P(io, T_FILE))
+ (void)rb_io_descriptor(io);
ossl_cb_state_begin();
}
@@ -1928,6 +1982,27 @@ ssl_call_end(VALUE self)
return saved_errno;
}
+static VALUE
+peer_ip_address(VALUE io)
+{
+ VALUE remote_address = rb_funcall(io, rb_intern("remote_address"), 0);
+
+ return rb_funcall(remote_address, rb_intern("inspect_sockaddr"), 0);
+}
+
+static VALUE
+fallback_peer_ip_address(VALUE self, VALUE exc)
+{
+ return rb_str_new_cstr("(null)");
+}
+
+static VALUE
+peeraddr_ip_str(VALUE self)
+{
+ VALUE io = ossl_ssl_get_io(self);
+ return rb_rescue(peer_ip_address, io, fallback_peer_ip_address, Qnil);
+}
+
static VALUE
ossl_start_ssl(VALUE self, int (*func)(SSL *), const char *funcname)
{
@@ -2697,6 +2772,227 @@ ossl_ssl_get_group(VALUE self)
}
#endif
+/*
+ * ossl_ssl_bio_meth
+ */
+static BIO *
+ossl_ssl_bio_setup(SSL *ssl)
+{
+ BIO *bio = BIO_new(ossl_ssl_bio_meth);
+ if (!bio)
+ ossl_raise(eOSSLError, "BIO_new");
+
+ BIO_set_data(bio, ssl);
+ BIO_set_init(bio, 1);
+ return bio;
+}
+
+struct bio_call_args {
+ int state_orig;
+ VALUE (*func)(VALUE);
+ VALUE args;
+};
+
+static VALUE
+bio_call_jump(VALUE args_)
+{
+ struct bio_call_args *args = (void *)args_;
+ rb_jump_tag(args->state_orig);
+}
+
+static VALUE
+bio_call_rescue(VALUE args_, VALUE exc)
+{
+ struct bio_call_args *args = (void *)args_;
+ return args->func(args->args);
+}
+
+static VALUE
+bio_call_pending(VALUE args_)
+{
+ return rb_rescue(bio_call_jump, args_, bio_call_rescue, args_);
+}
+
+/*
+ * BIO functions may be called by OpenSSL when something has already gone
+ * wrong, such as when a Ruby callback registered to SSLContext raised an
+ * exception or was interrupted by Thread#kill.
+ *
+ * Here, we execute func(args) when a jump is already pending, but only if it
+ * is an ordinary StandardError, because we don't want to swallow a fatal like
+ * Thread#kill.
+ */
+static int
+bio_call(VALUE (*func)(VALUE), VALUE args)
+{
+ struct ossl_err_state es;
+ int state, state_orig = ossl_cb_state_get();
+
+ ossl_err_state_save(&es);
+ if (!state_orig) {
+ rb_protect(func, args, &state);
+ if (state)
+ ossl_cb_state_set(state);
+ }
+ else {
+ struct bio_call_args pargs = { state_orig, func, args };
+ ossl_cb_state_end();
+ ossl_cb_state_begin();
+ rb_protect(bio_call_pending, (VALUE)&pargs, &state);
+ ossl_cb_state_set(state ? state : state_orig);
+ }
+ ossl_err_state_restore(&es);
+
+ errno = 0;
+#ifdef _WIN32
+ WSASetLastError(0);
+#endif
+ return !state;
+}
+
+struct bwrite_args {
+ BIO *bio;
+ const char *data;
+ int dlen;
+ int ret;
+};
+
+static VALUE
+bio_bwrite0(VALUE args_)
+{
+ struct bwrite_args *args = (void *)args_;
+ SSL *ssl;
+ VALUE self, io, buf, fargs[2], ret;
+
+ ssl = BIO_get_data(args->bio);
+ self = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
+ io = ossl_ssl_get_io(self);
+
+ buf = rb_attr_get(self, id_bio_wbuf);
+ if ((rb_len_t)rb_str_capacity(buf) >= args->dlen)
+ rb_str_modify(buf);
+ else
+ rb_str_modify_expand(buf, args->dlen - RSTRING_LEN(buf));
+ memcpy(RSTRING_PTR(buf), args->data, args->dlen);
+ rb_str_set_len(buf, args->dlen);
+
+ fargs[0] = buf;
+ fargs[1] = nonblock_kwargs;
+ ret = rb_funcallv_kw(io, id_write_nonblock, 2, fargs, RB_PASS_KEYWORDS);
+
+ if (RB_INTEGER_TYPE_P(ret)) {
+ int len = NUM2INT(ret);
+ if (len < 0 || len > args->dlen)
+ rb_raise(rb_eTypeError, "write_nonblock wrote too much data");
+ args->ret = len;
+ }
+ else if (ret == sym_wait_readable) {
+ BIO_set_retry_read(args->bio);
+ args->ret = -1;
+ }
+ else if (ret == sym_wait_writable) {
+ BIO_set_retry_write(args->bio);
+ args->ret = -1;
+ }
+ else {
+ rb_raise(rb_eTypeError, "write_nonblock must return an Integer, "
+ ":wait_readable, or :wait_writable");
+ }
+ return Qnil;
+}
+
+static int
+bio_bwrite(BIO *bio, const char *data, int dlen)
+{
+ struct bwrite_args args = { bio, data, dlen, -1 };
+ BIO_clear_retry_flags(bio);
+ if (bio_call(bio_bwrite0, (VALUE)&args))
+ return args.ret;
+ return -1;
+}
+
+struct bread_args {
+ BIO *bio;
+ char *data;
+ int dlen;
+ int ret;
+};
+
+static VALUE
+bio_bread0(VALUE args_)
+{
+ struct bread_args *args = (void *)args_;
+ SSL *ssl;
+ VALUE self, io, fargs[3], ret;
+
+ ssl = BIO_get_data(args->bio);
+ self = (VALUE)SSL_get_ex_data(ssl, ossl_ssl_ex_ptr_idx);
+ io = ossl_ssl_get_io(self);
+
+ fargs[0] = INT2NUM(args->dlen);
+ fargs[1] = rb_attr_get(self, id_bio_rbuf);
+ fargs[2] = nonblock_kwargs;
+ ret = rb_funcallv_kw(io, id_read_nonblock, 3, fargs, RB_PASS_KEYWORDS);
+
+ if (RB_TYPE_P(ret, T_STRING)) {
+ int len = RSTRING_LENINT(ret);
+ if (len > args->dlen)
+ rb_raise(rb_eTypeError, "read_nonblock returned too much data");
+ memcpy(args->data, RSTRING_PTR(ret), len);
+ args->ret = len;
+ }
+ else if (NIL_P(ret)) {
+#if OSSL_OPENSSL_PREREQ(3, 0, 0) && !OSSL_OPENSSL_PREREQ(4, 0, 0)
+ /*
+ * Only needed for OpenSSL 3.x. OpenSSL 4.x will automatically handle
+ * it based on the return value of 0 in the BIO layer.
+ *
+ * OpenSSL 1.1.1, LibreSSL, and AWS-LC don't use BIO_eof().
+ */
+ BIO_set_flags(args->bio, BIO_FLAGS_IN_EOF);
+#endif
+ args->ret = 0;
+ }
+ else if (ret == sym_wait_readable) {
+ BIO_set_retry_read(args->bio);
+ args->ret = -1;
+ }
+ else if (ret == sym_wait_writable) {
+ BIO_set_retry_write(args->bio);
+ args->ret = -1;
+ }
+ else {
+ rb_raise(rb_eTypeError, "read_nonblock must return a String, nil, "
+ ":wait_readable, or :wait_writable");
+ }
+ return Qnil;
+}
+
+static int
+bio_bread(BIO *bio, char *data, int dlen)
+{
+ struct bread_args args = { bio, data, dlen, -1 };
+ BIO_clear_retry_flags(bio);
+ if (bio_call(bio_bread0, (VALUE)&args))
+ return args.ret;
+ return -1;
+}
+
+static long
+bio_ctrl(BIO *bio, int cmd, long larg, void *parg)
+{
+ switch (cmd) {
+#if OSSL_OPENSSL_PREREQ(3, 0, 0) && !OSSL_OPENSSL_PREREQ(4, 0, 0)
+ case BIO_CTRL_EOF:
+ return BIO_test_flags(bio, BIO_FLAGS_IN_EOF) != 0;
+#endif
+ case BIO_CTRL_FLUSH:
+ return 1;
+ default:
+ return 0;
+ }
+}
+
#endif /* !defined(OPENSSL_NO_SOCK) */
void
@@ -3101,6 +3397,8 @@ Init_ossl_ssl(void)
rb_define_alloc_func(cSSLSocket, ossl_ssl_s_alloc);
rb_define_method(cSSLSocket, "initialize", ossl_ssl_initialize, -1);
rb_undef_method(cSSLSocket, "initialize_copy");
+ rb_define_method(cSSLSocket, "io", ossl_ssl_get_io, 0);
+ rb_define_alias(cSSLSocket, "to_io", "io");
rb_define_private_method(cSSLSocket, "ssl_connect", ossl_ssl_connect, 0);
rb_define_private_method(cSSLSocket, "ssl_accept", ossl_ssl_accept, 0);
rb_define_private_method(cSSLSocket, "string_new_capacity", ossl_ssl_string_new_capacity, 1);
@@ -3293,6 +3591,11 @@ Init_ossl_ssl(void)
id_npn_protocols_encoded = rb_intern_const("npn_protocols_encoded");
id_each = rb_intern_const("each");
id_original_context = rb_intern_const("original_context");
+ id_io = rb_intern_const("io");
+ id_read_nonblock = rb_intern_const("read_nonblock");
+ id_write_nonblock = rb_intern_const("write_nonblock");
+ id_bio_rbuf = rb_intern_const("bio_rbuf");
+ id_bio_wbuf = rb_intern_const("bio_wbuf");
#define DefIVarID(name) do \
id_i_##name = rb_intern_const("@"#name); while (0)
@@ -3323,9 +3626,28 @@ Init_ossl_ssl(void)
DefIVarID(keylog_cb);
DefIVarID(tmp_dh_callback);
- DefIVarID(io);
DefIVarID(context);
DefIVarID(hostname);
DefIVarID(sync_close);
+
+ int bio_index = BIO_get_new_index();
+ if (bio_index < 0)
+ rb_raise(rb_eRuntimeError, "BIO_get_new_index");
+ ossl_ssl_bio_meth = BIO_meth_new(BIO_TYPE_SOURCE_SINK | bio_index,
+ "Ruby IO-like object");
+ if (!ossl_ssl_bio_meth)
+ rb_raise(rb_eRuntimeError, "BIO_meth_new");
+ if (!BIO_meth_set_write(ossl_ssl_bio_meth, bio_bwrite) ||
+ !BIO_meth_set_read(ossl_ssl_bio_meth, bio_bread) ||
+ !BIO_meth_set_ctrl(ossl_ssl_bio_meth, bio_ctrl)) {
+ BIO_meth_free(ossl_ssl_bio_meth);
+ ossl_ssl_bio_meth = NULL;
+ rb_raise(rb_eRuntimeError, "BIO_meth_set_*");
+ }
+
+ nonblock_kwargs = rb_hash_new();
+ rb_hash_aset(nonblock_kwargs, ID2SYM(rb_intern_const("exception")), Qfalse);
+ rb_obj_freeze(nonblock_kwargs);
+ rb_global_variable(&nonblock_kwargs);
#endif /* !defined(OPENSSL_NO_SOCK) */
}
diff --git a/lib/openssl/buffering.rb b/lib/openssl/buffering.rb
index f611f2899..a0248572a 100644
--- a/lib/openssl/buffering.rb
+++ b/lib/openssl/buffering.rb
@@ -57,7 +57,7 @@ def initialize(*)
super
@eof = false
@rbuffer = String.new
- @sync = @io.sync
+ @sync = io.respond_to?(:sync) ? io.sync : true
end
#
@@ -168,10 +168,10 @@ def readpartial(maxlen, buf=nil)
# begin
# result = ssl.read_nonblock(maxlen)
# rescue IO::WaitReadable
- # IO.select([io])
+ # ssl.wait_readable
# retry
# rescue IO::WaitWritable
- # IO.select(nil, [io])
+ # ssl.wait_writable
# retry
# end
#
@@ -482,10 +482,10 @@ def write(*s)
# begin
# result = ssl.write_nonblock(str)
# rescue IO::WaitReadable
- # IO.select([io])
+ # ssl.wait_readable
# retry
# rescue IO::WaitWritable
- # IO.select(nil, [io])
+ # ssl.wait_writable
# retry
# end
#
diff --git a/lib/openssl/ssl.rb b/lib/openssl/ssl.rb
index d7de8b3dd..7112493f1 100644
--- a/lib/openssl/ssl.rb
+++ b/lib/openssl/ssl.rb
@@ -269,25 +269,6 @@ def wait_readable(*args)
def wait_writable(*args)
to_io.wait_writable(*args)
end
-
- if IO.method_defined?(:timeout)
- def timeout
- to_io.timeout
- end
-
- def timeout=(value)
- to_io.timeout=(value)
- end
- else
- def timeout
- nil
- end
-
- def timeout=(value)
- raise NotImplementedError,
- "IO#timeout= is not available on this Ruby version"
- end
- end
end
def verify_certificate_identity(cert, hostname)
@@ -380,10 +361,6 @@ class SSLSocket
attr_reader :hostname
- # The underlying IO object.
- attr_reader :io
- alias :to_io :io
-
# The SSLContext object used in this connection.
attr_reader :context
@@ -415,6 +392,23 @@ def sysclose
IO_TimeoutError = defined?(IO::TimeoutError) ? IO::TimeoutError : IOError
private_constant :IO_TimeoutError
+ def timeout
+ io = self.io
+ unless io.respond_to?(:timeout)
+ return nil
+ end
+ io.timeout
+ end
+
+ def timeout=(value)
+ io = self.io
+ unless io.respond_to?(:timeout=)
+ raise NotImplementedError,
+ "IO#timeout= is not available on this Ruby version"
+ end
+ io.timeout = value
+ end
+
private def blocking(timeout = self.timeout)
if timeout
remaining = timeout
@@ -471,10 +465,10 @@ def connect(timeout: self.timeout)
# begin
# ssl.connect_nonblock
# rescue IO::WaitReadable
- # IO.select([s2])
+ # ssl.wait_readable
# retry
# rescue IO::WaitWritable
- # IO.select(nil, [s2])
+ # ssl.wait_writable
# retry
# end
#
@@ -509,10 +503,10 @@ def accept(timeout: self.timeout)
# begin
# ssl.accept_nonblock
# rescue IO::WaitReadable
- # IO.select([s2])
+ # ssl.wait_readable
# retry
# rescue IO::WaitWritable
- # IO.select(nil, [s2])
+ # ssl.wait_writable
# retry
# end
#
diff --git a/test/openssl/test_buffering.rb b/test/openssl/test_buffering.rb
index 6a8cbad07..a863e0a2d 100644
--- a/test/openssl/test_buffering.rb
+++ b/test/openssl/test_buffering.rb
@@ -7,7 +7,7 @@ class OpenSSL::TestBuffering < OpenSSL::TestCase
class IO
include OpenSSL::Buffering
- attr_accessor :sync
+ attr_accessor :sync, :io
def initialize
@io = String.new
diff --git a/test/openssl/test_pair.rb b/test/openssl/test_pair.rb
index c51002125..385a0dcd2 100644
--- a/test/openssl/test_pair.rb
+++ b/test/openssl/test_pair.rb
@@ -457,14 +457,14 @@ def test_read_nonblock
assert_instance_of(OpenSSL::SSL::SSLErrorWaitReadable, err)
end
s1.write "abc\ndef\n"
- IO.select([s2])
+ s2.wait_readable
assert_equal("ab", s2.read_nonblock(2))
assert_equal("c\n", s2.gets)
ret = nil
assert_nothing_raised("[ruby-core:20298]") { ret = s2.read_nonblock(10) }
assert_equal("def\n", ret)
s1.close
- IO.select([s2])
+ s2.wait_readable
assert_raise(EOFError) { s2.read_nonblock(10) }
assert_raise(ArgumentError) { s2.read_nonblock(-1) }
@@ -475,14 +475,14 @@ def test_read_nonblock_no_exception
ssl_pair {|s1, s2|
assert_equal :wait_readable, s2.read_nonblock(10, exception: false)
s1.write "abc\ndef\n"
- IO.select([s2])
+ s2.wait_readable
assert_equal("ab", s2.read_nonblock(2, exception: false))
assert_equal("c\n", s2.gets)
ret = nil
assert_nothing_raised("[ruby-core:20298]") { ret = s2.read_nonblock(10, exception: false) }
assert_equal("def\n", ret)
s1.close
- IO.select([s2])
+ s2.wait_readable
assert_equal(nil, s2.read_nonblock(10, exception: false))
}
end
@@ -660,11 +660,28 @@ def test_close_write
end
end
-class OpenSSL::TestSSLPair < OpenSSL::TestCase
- include OpenSSL::TestPairM
- include OpenSSL::TestEOF
+module OpenSSL::TestSSLPairUtils
+ def socketpair
+ host = "127.0.0.1"
+ svr = TCPServer.new(host, 0)
+ svr.setsockopt(:TCP, :NODELAY, 1)
+ port = svr.connect_address.ip_port
- def ssl_pair
+ tcps = nil
+ th = Thread.new { tcps = svr.accept }
+
+ tcpc = TCPSocket.new(host, port)
+ tcpc.setsockopt(:TCP, :NODELAY, 1)
+ th.join
+
+ yield tcpc, tcps
+ ensure
+ tcpc&.close
+ tcps&.close
+ svr&.close
+ end
+
+ def do_handshake(tcpc, tcps)
svr_dn = OpenSSL::X509::Name.parse("/DC=org/DC=ruby-lang/CN=localhost")
ee_exts = [
["keyUsage", "keyEncipherment,digitalSignature", true],
@@ -672,14 +689,7 @@ def ssl_pair
svr_key = OpenSSL::TestUtils::Fixtures.pkey("rsa-1")
svr_cert = issue_cert(svr_dn, svr_key, 1, ee_exts, nil, nil)
- host = "127.0.0.1"
- svr = TCPServer.new(host, 0)
- svr.setsockopt(:TCP, :NODELAY, 1)
- port = svr.connect_address.ip_port
-
- tcps = nil
th = Thread.new {
- tcps = svr.accept
sctx = OpenSSL::SSL::SSLContext.new
sctx.add_certificate(svr_cert, svr_key)
ssl = OpenSSL::SSL::SSLSocket.new(tcps, sctx)
@@ -687,41 +697,58 @@ def ssl_pair
ssl
}
- tcpc = TCPSocket.new(host, port)
- tcpc.setsockopt(:TCP, :NODELAY, 1)
c = OpenSSL::SSL::SSLSocket.new(tcpc)
c.connect
s = th.value
- yield c, s
- ensure
- tcpc&.close
- tcps&.close
- svr&.close
+ [c, s]
end
end
-class OpenSSL::TestSocketPair < OpenSSL::TestCase
+class OpenSSL::TestSSLPair < OpenSSL::TestCase
include OpenSSL::TestPairM
include OpenSSL::TestEOF
+ include OpenSSL::TestSSLPairUtils
def ssl_pair
- host = "127.0.0.1"
- svr = TCPServer.new(host, 0)
- svr.setsockopt(:TCP, :NODELAY, 1)
- port = svr.connect_address.ip_port
+ socketpair do |tcpc, tcps|
+ yield do_handshake(tcpc, tcps)
+ end
+ end
+end
- tcps = nil
- th = Thread.new { tcps = svr.accept }
+class OpenSSL::TestSSLPairIOLike < OpenSSL::TestCase
+ include OpenSSL::TestPairM
+ include OpenSSL::TestEOF
+ include OpenSSL::TestSSLPairUtils
- tcpc = TCPSocket.new(host, port)
- tcpc.setsockopt(:TCP, :NODELAY, 1)
- th.join
+ class IOWrapper
+ attr_reader :io
+ alias to_io io
+ def initialize(io) @io = io end
+ def read_nonblock(*args, **kwargs) @io.read_nonblock(*args, **kwargs) end
+ def write_nonblock(*args, **kwargs) @io.write_nonblock(*args, **kwargs) end
+ def wait_readable(*args) @io.wait_readable(*args) end
+ def wait_writable(*args) @io.wait_writable(*args) end
+ def close() @io.close end
+ def closed?() @io.closed? end
+ end
- yield tcpc, tcps
- ensure
- tcpc&.close
- tcps&.close
- svr&.close
+ def ssl_pair
+ socketpair do |tcpc, tcps|
+ yield do_handshake(IOWrapper.new(tcpc), IOWrapper.new(tcps))
+ end
+ end
+end
+
+class OpenSSL::TestSocketPair < OpenSSL::TestCase
+ include OpenSSL::TestPairM
+ include OpenSSL::TestEOF
+ include OpenSSL::TestSSLPairUtils
+
+ def ssl_pair
+ socketpair do |tcpc, tcps|
+ yield tcpc, tcps
+ end
end
end if RUBY_ENGINE != "truffleruby"
diff --git a/test/openssl/test_ssl.rb b/test/openssl/test_ssl.rb
index 2f9bac109..9ba6a5b30 100644
--- a/test/openssl/test_ssl.rb
+++ b/test/openssl/test_ssl.rb
@@ -4,17 +4,6 @@
if defined?(OpenSSL::SSL)
class OpenSSL::TestSSL < OpenSSL::SSLTestCase
- def test_bad_socket
- bad_socket = Struct.new(:sync).new
- assert_raise TypeError do
- socket = OpenSSL::SSL::SSLSocket.new bad_socket
- # if the socket is not a T_FILE, `connect` will segv because it tries
- # to get the underlying file descriptor but the API it calls assumes
- # the object type is T_FILE
- socket.connect
- end
- end
-
def test_ctx_setup
ctx = OpenSSL::SSL::SSLContext.new
assert_equal true, ctx.setup
@@ -246,6 +235,179 @@ def test_low_level_socket
end
end
+ private def make_io_like(sock)
+ klass = Class.new
+ required = %i[
+ read_nonblock
+ write_nonblock
+ wait_readable
+ wait_writable
+ close
+ closed?
+ ]
+ required.each do |name|
+ klass.define_method(name) { |*args, **kwargs|
+ sock.__send__(__method__, *args, **kwargs)
+ }
+ end
+ klass.new
+ end
+
+ def test_io_like
+ start_server do |port|
+ sock = TCPSocket.new("127.0.0.1", port)
+ obj = make_io_like(sock)
+
+ ssl = OpenSSL::SSL::SSLSocket.new(obj)
+ assert_same(obj, ssl.to_io)
+
+ ssl.connect
+ ssl.puts("abc"); assert_equal("abc\n", ssl.gets)
+ ensure
+ ssl&.close
+ sock&.close
+ end
+ end
+
+ def test_io_like_nested
+ server_proc = proc do |sock|
+ ssl = OpenSSL::SSL::SSLSocket.new(sock, make_server_context)
+ ssl.accept
+
+ nested = OpenSSL::SSL::SSLSocket.new(ssl, make_server_context)
+ nested.accept
+
+ readwrite_loop(nested)
+ ssl.close
+ end
+ start_server_proc(server_proc) do |port|
+ server_connect(port) do |ssl|
+ nested = OpenSSL::SSL::SSLSocket.new(ssl)
+ nested.connect
+ nested.puts("abc"); assert_equal("abc\n", nested.gets)
+ nested.close
+ end
+ end
+ end
+
+ def test_io_like_eof_without_close_notify
+ unless openssl?(3, 0, 0) || aws_lc?
+ omit "OpenSSL 1.1.1 and LibreSSL do not distinguish unexpected EOF"
+ end
+
+ server_proc = proc do |sock|
+ ssl = OpenSSL::SSL::SSLSocket.new(sock, make_server_context).accept
+ ssl.puts(ssl.gets)
+ sock.close_write
+ end
+ start_server_proc(server_proc) do |port|
+ sock = TCPSocket.new("127.0.0.1", port)
+ obj = make_io_like(sock)
+ ssl = OpenSSL::SSL::SSLSocket.new(obj)
+ ssl.connect
+ ssl.puts("abc")
+ assert_equal("abc\n", ssl.gets)
+ assert_raise(OpenSSL::SSL::SSLError) { ssl.sysread(1) }
+ ensure
+ ssl&.close
+ sock&.close
+ end
+ end
+
+ def test_io_like_write_nonblock_exception
+ start_server(ignore_listener_error: true) do |port|
+ sock = TCPSocket.new("127.0.0.1", port)
+ obj = make_io_like(sock)
+
+ # SSLSocket#connect calls write_nonblock at least twice: to write
+ # ClientHello and Finished. Let's raise an exception in the 2nd call.
+ called = 0
+ obj.define_singleton_method(:write_nonblock) { |*args, **kwargs|
+ raise "foo" if (called += 1) == 2
+ sock.write_nonblock(*args, **kwargs)
+ }
+
+ ssl = OpenSSL::SSL::SSLSocket.new(obj)
+ assert_raise_with_message(RuntimeError, "foo") { ssl.connect }
+ ensure
+ ssl&.close
+ sock&.close
+ end
+ end
+
+ def test_io_like_cb_exc
+ server_proc = proc do |sock|
+ obj = make_io_like(sock)
+ ctx = OpenSSL::SSL::SSLContext.new
+ ctx.servername_cb = -> ssl { raise "in servername_cb" }
+ ssl = OpenSSL::SSL::SSLSocket.new(obj, ctx)
+ assert_raise_with_message(RuntimeError, "in servername_cb") { ssl.accept }
+ end
+ start_server_proc(server_proc) do |port|
+ assert_raise_with_message(OpenSSL::SSL::SSLError, /unrecognized.name/i) {
+ server_connect(port, hostname: "localhost")
+ }
+ end
+ end
+
+ def test_io_like_cb_exc_write_exc
+ # If SSLContext#servername_cb fails, it must send the "unrecognized_name"
+ # alert. If another error occurs while writing the alert to the underlying
+ # socket, the original exception from the servername_cb is suppressed and
+ # the new exception is raised.
+ server_proc = proc do |sock|
+ called = []
+ obj = make_io_like(sock)
+ obj.define_singleton_method(:write_nonblock) { |*args, **kwargs|
+ called << :write_nonblock
+ raise "write_nonblock"
+ }
+ ctx = make_server_context
+ ctx.servername_cb = -> ssl {
+ called << :servername_cb
+ raise "servername_cb"
+ }
+ ssl = OpenSSL::SSL::SSLSocket.new(obj, ctx)
+ assert_raise_with_message(RuntimeError, "write_nonblock") { ssl.accept }
+ assert_equal([:servername_cb, :write_nonblock], called)
+ ensure
+ sock.close_write
+ end
+ start_server_proc(server_proc) do |port|
+ assert_raise(OpenSSL::SSL::SSLError) {
+ server_connect(port, hostname: "localhost")
+ }
+ end
+ end
+
+ def test_io_like_cb_throw_write_skipped
+ # If the pending jump is not a StandardError, we do not attempt to write to
+ # the underlying socket to avoid suppressing important jumps.
+ server_proc = proc do |sock|
+ called = []
+ obj = make_io_like(sock)
+ obj.define_singleton_method(:write_nonblock) { |*args, **kwargs|
+ called << :write_nonblock
+ raise "write_nonblock"
+ }
+ ctx = make_server_context
+ ctx.servername_cb = -> ssl {
+ called << :servername_cb
+ throw :servername_cb
+ }
+ ssl = OpenSSL::SSL::SSLSocket.new(obj, ctx)
+ assert_throw(:servername_cb) { ssl.accept }
+ assert_equal([:servername_cb], called)
+ ensure
+ sock.close_write
+ end
+ start_server_proc(server_proc) do |port|
+ assert_raise(OpenSSL::SSL::SSLError) {
+ server_connect(port, hostname: "localhost")
+ }
+ end
+ end
+
def test_socket_open
start_server { |port|
begin
@@ -1984,6 +2146,33 @@ def test_close_after_socket_close
}
end
+ def test_callback_close_underlying
+ omit "LibreSSL does not call session_new_cb in TLS 1.3" if libressl?
+
+ server_proc = proc do |sock|
+ ssl = OpenSSL::SSL::SSLSocket.new(sock, make_server_context).accept
+ readwrite_loop(ssl)
+ rescue SystemCallError, OpenSSL::SSL::SSLError
+ end
+ start_server_proc(server_proc) do |port|
+ sock = TCPSocket.new("127.0.0.1", port)
+ sock2 = TCPSocket.for_fd(sock.fileno)
+ sock2.autoclose = false
+ ctx = OpenSSL::SSL::SSLContext.new
+ ctx.session_cache_mode = OpenSSL::SSL::SSLContext::SESSION_CACHE_CLIENT
+ ctx.session_new_cb = proc do |ssl, session|
+ sock2.close
+ end
+ ssl = OpenSSL::SSL::SSLSocket.new(sock2, ctx)
+ ssl.connect
+ ssl.puts("abc")
+ assert_raise(Errno::EBADF, Errno::ENOTSOCK) { ssl.gets }
+ assert_raise(IOError) { ssl.puts("abc") }
+ ensure
+ sock&.close
+ end
+ end
+
def test_ssl_shutdown
server_can_close = Thread::Queue.new
server_proc = proc do |sock|
@@ -2626,10 +2815,11 @@ def test_ractor_set_params
private
- def server_connect(port, ctx = nil)
+ def server_connect(port, ctx = nil, hostname: nil)
sock = TCPSocket.new("127.0.0.1", port)
ssl = ctx ? OpenSSL::SSL::SSLSocket.new(sock, ctx) : OpenSSL::SSL::SSLSocket.new(sock)
ssl.sync_close = true
+ ssl.hostname = hostname if hostname
ssl.connect
yield ssl if block_given?
ensure