Repository navigation
Add DTLSContext and DTLSSocket for DTLS - #1172
team-milestone-alfonso wants to merge 10 commits into
Conversation
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
5cb43c5 to
49b873d
Compare
|
Force-pushed: The windows-latest 2.7 failure is in |
|
Thanks for the PR!
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.
Could we leave these for follow-up PRs after we have a basic DTLS support? I'll review the rest more closely later. |
| /* DTLSSocket takes a DTLSContext, and SSLSocket does not */ | ||
| static void | ||
| ssl_check_ctx_class(VALUE self, VALUE v_ctx) |
There was a problem hiding this comment.
I think we can let OpenSSL check this for us.
There was a problem hiding this comment.
OpenSSL doesn't seem to check it. Without this function, on OpenSSL 3.6.4 and 4.1.0:
- A
DTLSSocketwith anSSLContextsends 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
SSLSocketwith aDTLSContextcompletes a DTLS handshake, over TCP as well as UDP, but nothing handles the timer. - A
servername_cbthat returns the other kind of context works, sinceSSL_set_SSL_CTX()doesn't change the method of theSSL.
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?
| /* | ||
| * 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"); |
There was a problem hiding this comment.
Is this necessary? It feels weird that we have to check the BIO's status and the error queue to see this.
There was a problem hiding this comment.
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?
|
|
||
| class OpenSSL::TestDTLS < OpenSSL::SSLTestCase | ||
| # An IO-like object that carries datagrams to its peer in memory | ||
| class DatagramPipe |
There was a problem hiding this comment.
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
49b873d to
3127378
Compare
|
Thanks for the review. Force-pushed:
The context check and |
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:
DTLSContextandDTLSSocket, for one peer over a connectedUDPSocketor an IO-like object. The classes are defined with OpenSSL 3.2 or later that has DTLS enabled, since they useSSL_get_event_timeout()andSSL_handle_events()with no fallback toDTLSv1_get_timeout()andDTLSv1_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
UDPSocketis given toSSL_set_fd(), as any other socket is inSSLSocket. 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=andDTLSSocket#srtp_profile, andDTLSSocket.open. Until#mtu=is there, OpenSSL uses its minimum of 256 bytes for the datagrams of the handshake, because neitherBIO_s_socket()norossl_ssl_bio_methcan tell it the MTU. Application data is not limited by it.Also left for later: a listener, for which
SSL_new_listener()andSSL_accept_connection()support DTLS from OpenSSL 4.1 and could returnDTLSSocketobjects without changing what is here; a default for the MTU; and the DTLSOP_*constants that are under#if 0inossl_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_nonblockof an IO-like object leaves the connection in the error state, and later reads and writes raiseSSLError. With 3.6.4 the connection stays usable.ssl: factor out sslctx_alloc() from ossl_sslctx_s_alloc()
Let the caller choose the
SSL_METHODthat is passed toSSL_CTX_new().This prepares for an upcoming patch to add a subclass of
SSLContextthat usesDTLS_method(). No behavior change is intended.ssl: add DTLSContext and DTLSSocket
Currently, an
SSLContextis always created withTLS_method(), so ruby/openssl cannot be used for DTLS.Add
OpenSSL::SSL::DTLSContext, a subclass ofSSLContextthat is created withDTLS_method(), andOpenSSL::SSL::DTLSSocket, a subclass ofSSLSocketto be used with it.DTLSSocket.newrequires aDTLSContext, andSSLSocket.newdoes not accept one. The same applies to anSSLContextreturned bySSLContext#servername_cb.A
DTLSSocketis the connection with one peer. Its underlying socket is aUDPSocketthat is connected to the peer, or an IO-like object whose#read_nonblockand#write_nonblockhandle 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 ofSSLSocket, take:DTLS1,:DTLS1_2, and:DTLS1_3in the same way as the TLS versions. Also, add the constantsOpenSSL::SSL::DTLS1_VERSION,DTLS1_2_VERSION, andDTLS1_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_methaccepts 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
TypeErrorin DTLS if#write_nonblockof an IO-like object returns less than the length of the datagram.:wait_readableand:wait_writablework as before.ssl: add DTLSSocket#event_timeout and #handle_events
Expose
SSL_get_event_timeout()andSSL_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 callSSL_handle_events()when the time reported bySSL_get_event_timeout()has passed.The method names are those used for QUIC in #1008.
Unlike in that pull request,
#handle_eventsdoes not raise for every failure ofSSL_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 theBIO_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#syswriteof aDTLSSocketonly wait for the underlying socket. If a handshake message is lost, nothing sends it again.Override
SSLSocket#blockinginDTLSSocketso that they wait no longer than#event_timeoutat a time, and call#handle_eventsbefore retrying. This is not limited to the handshake. With DTLS 1.3, the timer is still running when#acceptreturns, 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_readableor#wait_writableno 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::Bufferingcollect strings in a buffer in#do_write, and pass the buffer to#syswritewhen#syncis 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:sync = false, the strings given to separate calls are joined into one record. The peer reads"onetwo"afterwrite("one"),write("two"), andflush.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#flushfail too, and#closediscards it.#syncis, a string that could not be written stays in the buffer. The next write sends both as one record, or fails again.Override
#do_writeinDTLSSocketto pass each string to#syswriteat once, so that there is nothing for#flushto do. As before withsync = true,#writesends one record for each argument, and#<<,#puts,#print,#printf, and#putcsend 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