Skip to content

Add DTLSContext and DTLSSocket for DTLS - #1172

Draft
team-milestone-alfonso wants to merge 10 commits into
ruby:masterfrom
team-milestone-alfonso:dtls-first-step
Draft

team-milestone-alfonso wants to merge 10 commits into
ruby:masterfrom
team-milestone-alfonso:dtls-first-step

Conversation

@team-milestone-alfonso

@team-milestone-alfonso team-milestone-alfonso commented Nov 30, 2026 •

Copy link
Copy Markdown

Applies on top of #736, up to 997dd5f and without [DO NOT MERGE] Always use Ruby IO. The first three commits here are from that PR; the four before them were merged with #1168.

This is a draft of the first step discussed in #1169: DTLSContext and DTLSSocket, for one peer over a connected UDPSocket or an IO-like object. The classes are defined with OpenSSL 3.2 or later that has DTLS enabled, since they use SSL_get_event_timeout() and SSL_handle_events() with no fallback to DTLSv1_get_timeout() and DTLSv1_handle_timeout().

The test suite passes on my box with OpenSSL 3.6.4 and 4.1.0, on Ruby 2.7 and 4.0 on macOS.

A UDPSocket is given to SSL_set_fd(), as any other socket is in SSLSocket. A zero-length datagram from the peer's address therefore fails the handshake or ends the connection with "unexpected eof while reading". This is left to openssl/openssl#34027.

Left for follow-up PRs: DTLSSocket#mtu=, DTLSContext#srtp_profiles= and DTLSSocket#srtp_profile, and DTLSSocket.open. Until #mtu= is there, OpenSSL uses its minimum of 256 bytes for the datagrams of the handshake, because neither BIO_s_socket() nor ossl_ssl_bio_meth can tell it the MTU. Application data is not limited by it.

Also left for later: a listener, for which SSL_new_listener() and SSL_accept_connection() support DTLS from OpenSSL 4.1 and could return DTLSSocket objects without changing what is here; a default for the MTU; and the DTLS OP_* constants that are under #if 0 in ossl_ssl.c. DTLSv1_listen() is not bound.

One difference between the libraries that is left as it is: with OpenSSL 4.1.0, an exception raised by write_nonblock of an IO-like object leaves the connection in the error state, and later reads and writes raise SSLError. With 3.6.4 the connection stays usable.


ssl: factor out sslctx_alloc() from ossl_sslctx_s_alloc()

Let the caller choose the SSL_METHOD that is passed to SSL_CTX_new().

This prepares for an upcoming patch to add a subclass of SSLContext that uses DTLS_method(). No behavior change is intended.


ssl: add DTLSContext and DTLSSocket

Currently, an SSLContext is always created with TLS_method(), so ruby/openssl cannot be used for DTLS.

Add OpenSSL::SSL::DTLSContext, a subclass of SSLContext that is created with DTLS_method(), and OpenSSL::SSL::DTLSSocket, a subclass of SSLSocket to be used with it. DTLSSocket.new requires a DTLSContext, and SSLSocket.new does not accept one. The same applies to an SSLContext returned by SSLContext#servername_cb.

A DTLSSocket is the connection with one peer. Its underlying socket is a UDPSocket that is connected to the peer, or an IO-like object whose #read_nonblock and #write_nonblock handle one whole datagram at a time. Accepting connections from unknown peers is left for later.

The classes are defined only if SSL_get_event_timeout() is available and DTLS is not disabled in OpenSSL. The function was added in OpenSSL 3.2 and is needed for retransmission, which follows in another patch.

See #1169 for the discussion.


ssl: support DTLS versions in #min_version= and #max_version=

Let SSLContext#min_version= and #max_version=, and those of SSLSocket, take :DTLS1, :DTLS1_2, and :DTLS1_3 in the same way as the TLS versions. Also, add the constants OpenSSL::SSL::DTLS1_VERSION, DTLS1_2_VERSION, and DTLS1_3_VERSION.

DTLS 1.3 is in OpenSSL 4.1 or later.

OpenSSL ignores a TLS version given to a context for DTLS, and a DTLS version given to a context for TLS. This is left as it is.


ssl: reject short writes of datagrams in DTLSSocket

Currently, ossl_ssl_bio_meth accepts any number of bytes up to the length of the data as the result of #write_nonblock. This is right for a stream, where OpenSSL writes the rest later. In DTLS, OpenSSL then sends the rest of the record as another datagram, and the peer cannot use either of them.

Raise TypeError in DTLS if #write_nonblock of an IO-like object returns less than the length of the datagram. :wait_readable and :wait_writable work as before.


ssl: add DTLSSocket#event_timeout and #handle_events

Expose SSL_get_event_timeout() and SSL_handle_events(), added in OpenSSL 3.2. DTLS sends its handshake messages again if the peer does not answer in time, but OpenSSL leaves the timer to the application. It has to call SSL_handle_events() when the time reported by SSL_get_event_timeout() has passed.

The method names are those used for QUIC in #1008.

Unlike in that pull request, #handle_events does not raise for every failure of SSL_handle_events(). The function fails with nothing in the error queue if the underlying socket is not ready to send a flight again and the flight takes more than one datagram. With a flight that fits in one datagram, it does not fail at all, because OpenSSL ignores the result of the BIO_flush() that writes it. This is not an error for the caller either way: OpenSSL has restarted the timer and sends the messages when it expires the next time. So the failure is ignored if the BIO asked for a retry during the call and the error queue is empty.


ssl: handle the DTLS timer in blocking methods of DTLSSocket

Currently, #connect, #accept, #sysread, and #syswrite of a DTLSSocket only wait for the underlying socket. If a handshake message is lost, nothing sends it again.

Override SSLSocket#blocking in DTLSSocket so that they wait no longer than #event_timeout at a time, and call #handle_events before retrying. This is not limited to the handshake. With DTLS 1.3, the timer is still running when #accept returns, until the client acknowledges the NewSessionTicket messages.

The timeout given by the caller remains the limit for the whole operation, and a retransmission does not extend it. Since a wait now ends when the timer expires too, a falsy result of #wait_readable or #wait_writable no longer means that the time is up. So check the deadline after each wait, whether or not the underlying socket is ready. A datagram that DTLS discards makes the socket readable without the operation making progress. A record that arrives after the timeout is left for the next read.


ssl: do not buffer writes in DTLSSocket

Currently, the writing methods of OpenSSL::Buffering collect strings in a buffer in #do_write, and pass the buffer to #syswrite when #sync is true or when it has more than 16384 bytes. In DTLS, SSL_write() sends its argument as one record in one datagram, or fails. The two do not work together:

  • With sync = false, the strings given to separate calls are joined into one record. The peer reads "onetwo" after write("one"), write("two"), and flush.
  • With sync = false, the buffer is not written until it has more than a record can hold. SSL_write() then fails with "dtls message too big". The buffer is kept, so every later write and #flush fail too, and #close discards it.
  • Whatever #sync is, a string that could not be written stays in the buffer. The next write sends both as one record, or fails again.

Override #do_write in DTLSSocket to pass each string to #syswrite at once, so that there is nothing for #flush to do. As before with sync = true, #write sends one record for each argument, and #<<, #puts, #print, #printf, and #putc send one record for each call.

The reading methods are left as they are. SSL_read() keeps the rest of a record for the next call in DTLS too, so #read, #gets, and the others return every byte that arrives. They do not keep the boundaries of records.

🤖 Generated with Claude Code

https://claude.ai/code/session_01FZx6aiXzbk9q7ePqfHfYND

rhenium and others added 4 commits November 28, 2026 03:15
It should be stored in a hidden ivar instead of [@]io.
Make the following methods optional on the underlying socket:

  - #remote_address: used only to provide additional information in
    error messages.
  - #timeout: assume nil if not implemented.
  - #sync: assume true if not implemented.

This prepares for an upcoming patch to allow arbitrary IO-like objects
as the underlying socket, for which we want to keep the requirements to
a minimum.
Currently, OpenSSL::SSL::SSLSocket.new requires a T_FILE object because
we pass the file descriptor to OpenSSL. Relax this and allow any Ruby
object that responds to Ruby's standard non-blocking IO interface,
namely:

  - write_nonblock, read_nonblock
  - wait_readable, wait_writable
  - close, closed?

To support this, we can provide a custom BIO_METHOD that maps BIO
operation to a Ruby method call.

This continues to use the current BIO_s_socket() BIO_METHOD if a T_FILE
is passed because it is more efficient in that case. No behavior change
is intended for existing users.
Let the caller choose the SSL_METHOD that is passed to SSL_CTX_new().

This prepares for an upcoming patch to add a subclass of SSLContext
that uses DTLS_method(). No behavior change is intended.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FZx6akiL17gVLQTiixKJZo
@team-milestone-alfonso

Copy link
Copy Markdown
Author

Force-pushed: test_closed_socket now skips its UDPSocket part on TruffleRuby. TruffleRuby's IO#close does not wake up IO#wait_readable in another thread, so the read waited until the DTLS timer fired (macOS) or forever (Linux, hitting the 5-minute step timeout).

The windows-latest 2.7 failure is in test_ctx_client_session_cb_tls13_exception, where the TCP server got ECONNABORTED. It looks unrelated to this PR.

@rhenium

rhenium commented Dec 2, 2026

Copy link
Copy Markdown
Member

Thanks for the PR!

I'd like your view on ssl: ignore zero-length datagrams in DTLSSocket in particular. It is the concrete form of my correction in #1169 (comment).

https://redirect.github.com/openssl/openssl/pull/34027 appears to be a bug in OpenSSL that affects all DTLS users, so it should be fixed there. I'd rather not introduce a workaround in ruby/openssl for now, especially since the fix seems likely to be backported to all stable branches.

ssl: add DTLSSocket#mtu=
ssl: add DTLSContext#srtp_profiles= and DTLSSocket#srtp_profile
ssl: add DTLSSocket.open

Could we leave these for follow-up PRs after we have a basic DTLS support?

I'll review the rest more closely later.

Comment thread ext/openssl/ossl_ssl.c
Comment on lines +517 to +519
/* DTLSSocket takes a DTLSContext, and SSLSocket does not */
static void
ssl_check_ctx_class(VALUE self, VALUE v_ctx)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can let OpenSSL check this for us.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OpenSSL doesn't seem to check it. Without this function, on OpenSSL 3.6.4 and 4.1.0:

  • A DTLSSocket with an SSLContext sends TLS records over the UDP socket. Against a DTLS server, both ends wait forever, because the server discards them. As a server, it raises "wrong version number" in #accept.
  • An SSLSocket with a DTLSContext completes a DTLS handshake, over TCP as well as UDP, but nothing handles the timer.
  • A servername_cb that returns the other kind of context works, since SSL_set_SSL_CTX() doesn't change the method of the SSL.

So I'd drop the check for servername_cb and keep the one in #initialize, but ask OpenSSL with SSL_is_dtls() instead of looking at the class. Or would you rather remove both?

Comment thread ext/openssl/ossl_ssl.c
Comment on lines +2946 to +2952
/*
* In DTLS 1.3, SSL_handle_events() fails if the underlying socket is not
* ready. This is not an error: OpenSSL has restarted the timer, so it is
* the same as losing the retransmission.
*/
if (!ret && !(bio && BIO_should_retry(bio) && !ERR_peek_error()))
ossl_raise(eSSLError, "SSL_handle_events");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this necessary? It feels weird that we have to check the BIO's status and the error queue to see this.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's for a flight that can't be written when the timer expires. SSL_handle_events() then returns 0 with nothing in the error queue (SSL_get_error() gives SSL_ERROR_WANT_WRITE), and OpenSSL has already restarted the timer.

The code comment is wrong about DTLS 1.3: it depends on whether the flight takes more than one datagram. A flight that fits in one datagram is only written by the final BIO_flush() in dtls1_retransmit_message(), whose result is ignored. With the minimum MTU of 256 bytes that OpenSSL uses when none is set, a DTLS 1.2 server's first flight hits it too, on 3.6.4 and 4.1.0.

If #handle_events raised here, so would a blocking #connect, #accept or #sysread. With a UDPSocket it needs send() to fail with EAGAIN, which I couldn't get on loopback. With an IO-like object, it's write_nonblock returning :wait_writable.

I could switch on SSL_get_error() instead, as ossl_ssl_shutdown() does, and return nil for SSL_ERROR_WANT_WRITE, though its man page doesn't list SSL_handle_events(). Or raise for every failure as #1008 does. Which would you prefer?

Comment thread test/openssl/test_dtls.rb Outdated

class OpenSSL::TestDTLS < OpenSSL::SSLTestCase
# An IO-like object that carries datagrams to its peer in memory
class DatagramPipe

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should primarily test it with an actual socket pair.

Currently, an SSLContext is always created with TLS_method(), so
ruby/openssl cannot be used for DTLS.

Add OpenSSL::SSL::DTLSContext, a subclass of SSLContext that is created
with DTLS_method(), and OpenSSL::SSL::DTLSSocket, a subclass of
SSLSocket to be used with it. DTLSSocket.new requires a DTLSContext,
and SSLSocket.new does not accept one. The same applies to an
SSLContext returned by SSLContext#servername_cb.

A DTLSSocket is the connection with one peer. Its underlying socket is
a UDPSocket that is connected to the peer, or an IO-like object whose
#read_nonblock and #write_nonblock handle one whole datagram at a time.
Accepting connections from unknown peers is left for later.

The classes are defined only if SSL_get_event_timeout() is available
and DTLS is not disabled in OpenSSL. The function was added in OpenSSL
3.2 and is needed for retransmission, which follows in another patch.

See ruby#1169 for the discussion.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FZx6akiL17gVLQTiixKJZo
Let SSLContext#min_version= and #max_version=, and those of SSLSocket,
take :DTLS1, :DTLS1_2, and :DTLS1_3 in the same way as the TLS
versions. Also, add the constants OpenSSL::SSL::DTLS1_VERSION,
DTLS1_2_VERSION, and DTLS1_3_VERSION.

DTLS 1.3 is in OpenSSL 4.1 or later.

OpenSSL ignores a TLS version given to a context for DTLS, and a DTLS
version given to a context for TLS. This is left as it is.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FZx6akiL17gVLQTiixKJZo
Currently, ossl_ssl_bio_meth accepts any number of bytes up to the
length of the data as the result of #write_nonblock. This is right for
a stream, where OpenSSL writes the rest later. In DTLS, OpenSSL then
sends the rest of the record as another datagram, and the peer cannot
use either of them.

Raise TypeError in DTLS if #write_nonblock of an IO-like object returns
less than the length of the datagram. :wait_readable and :wait_writable
work as before.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FZx6akiL17gVLQTiixKJZo
Expose SSL_get_event_timeout() and SSL_handle_events(), added in
OpenSSL 3.2. DTLS sends its handshake messages again if the peer does
not answer in time, but OpenSSL leaves the timer to the application. It
has to call SSL_handle_events() when the time reported by
SSL_get_event_timeout() has passed.

The method names are those used for QUIC in
ruby#1008.

Unlike in that pull request, #handle_events does not raise for every
failure of SSL_handle_events(). The function fails with nothing in the
error queue if the underlying socket is not ready to send a flight
again and the flight takes more than one datagram. With a flight that
fits in one datagram, it does not fail at all, because OpenSSL ignores
the result of the BIO_flush() that writes it. This is not an error for
the caller either way: OpenSSL has restarted the timer and sends the
messages when it expires the next time. So the failure is ignored if
the BIO asked for a retry during the call and the error queue is empty.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FZx6akiL17gVLQTiixKJZo
Currently, #connect, #accept, #sysread, and #syswrite of a DTLSSocket
only wait for the underlying socket. If a handshake message is lost,
nothing sends it again.

Override SSLSocket#blocking in DTLSSocket so that they wait no longer
than #event_timeout at a time, and call #handle_events before retrying.
This is not limited to the handshake. With DTLS 1.3, the timer is still
running when #accept returns, until the client acknowledges the
NewSessionTicket messages.

The timeout given by the caller remains the limit for the whole
operation, and a retransmission does not extend it. Since a wait now
ends when the timer expires too, a falsy result of #wait_readable or
#wait_writable no longer means that the time is up. So check the
deadline after each wait, whether or not the underlying socket is
ready. A datagram that DTLS discards makes the socket readable without
the operation making progress. A record that arrives after the timeout
is left for the next read.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FZx6akiL17gVLQTiixKJZo
Currently, the writing methods of OpenSSL::Buffering collect strings in
a buffer in #do_write, and pass the buffer to #syswrite when #sync is
true or when it has more than 16384 bytes. In DTLS, SSL_write() sends
its argument as one record in one datagram, or fails. The two do not
work together:

  - With sync = false, the strings given to separate calls are joined
    into one record. The peer reads "onetwo" after write("one"),
    write("two"), and flush.
  - With sync = false, the buffer is not written until it has more
    than a record can hold. SSL_write() then fails with "dtls message
    too big". The buffer is kept, so every later write and #flush fail
    too, and #close discards it.
  - Whatever #sync is, a string that could not be written stays in the
    buffer. The next write sends both as one record, or fails again.

Override #do_write in DTLSSocket to pass each string to #syswrite at
once, so that there is nothing for #flush to do. As before with sync =
true, #write sends one record for each argument, and #<<, #puts,
#print, #printf, and #putc send one record for each call.

The reading methods are left as they are. SSL_read() keeps the rest of
a record for the next call in DTLS too, so #read, #gets, and the others
return every byte that arrives. They do not keep the boundaries of
records.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FZx6akiL17gVLQTiixKJZo
@team-milestone-alfonso

Copy link
Copy Markdown
Author

Thanks for the review. Force-pushed:

  • Dropped ssl: ignore zero-length datagrams in DTLSSocket. A UDPSocket goes to SSL_set_fd() again, as in SSLSocket, and empty datagrams are left to [CVE-2026-133881] DTLS: discard empty datagrams on BIO reads openssl/openssl#34027. With a local build of 4.1.0 plus that patch, they are discarded on this path.
  • Moved DTLSSocket#mtu=, DTLSContext#srtp_profiles=, DTLSSocket#srtp_profile and DTLSSocket.open out, for follow-up PRs. Until #mtu= is there, the handshake uses datagrams of at most 256 bytes, which is the minimum that OpenSSL falls back to.
  • The tests use a pair of UDPSockets. Where a test has to count, refuse or cut datagrams, it wraps one of them in an IO-like object, with a copy of make_io_like from test_ssl.rb. DatagramPipe is gone.

The context check and #handle_events are unchanged, pending the two inline threads. I only corrected the comment and the commit message that were wrong about DTLS 1.3. test_event_timeout now blocks the server's first flight, which takes several datagrams, so it gets the failure of SSL_handle_events() with DTLS 1.2 as well.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants