diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0956183d50b..357ad8f1e6b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -310,6 +310,9 @@ jobs: - target: minimized compiler: gcc host_os: ubuntu-26.04 + - target: no_dtls13 + compiler: gcc + host_os: ubuntu-26.04 - target: no_tls12 compiler: gcc host_os: ubuntu-26.04 @@ -356,7 +359,7 @@ jobs: repository: ${{ env.BORINGSSL_REPO }} ref: ${{ env.BORINGSSL_BRANCH }} path: ./boringssl - if: matrix.target == 'no_tls12' || matrix.target == 'no_tls13' + if: matrix.target == 'no_dtls13' || matrix.target == 'no_tls12' || matrix.target == 'no_tls13' - name: Setup Build Agent uses: ./source/.github/actions/setup-build-agent diff --git a/doc/api_ref/tls.rst b/doc/api_ref/tls.rst index 6ec97c6ca62..e143267f7aa 100644 --- a/doc/api_ref/tls.rst +++ b/doc/api_ref/tls.rst @@ -4,7 +4,7 @@ Transport Layer Security (TLS) Botan has client and server implementations of TLS 1.2 and 1.3. Support for older versions of the protocol was removed with Botan 3.0. -There is also support for DTLS (currently v1.2 only), a variant of TLS +There is also support for DTLS 1.2 and 1.3 (experimental), a variant of TLS adapted for operation on datagram transports such as UDP and SCTP. DTLS support should be considered as beta quality and further testing is invited. @@ -212,16 +212,18 @@ additional information about the connection. std::function op) .. - TODO(Botan4): When timeout_check is removed, this becomes _required_ for DTLS. + TODO(Botan4): When timeout_check is removed, this becomes _required_ + for DTLS 1.2 as well. - Optional, but recommended for DTLS. This callback is used to schedule a - deferred operation to be invoked after a specified number of milliseconds. - This is used by DTLS to schedule retransmissions of handshake messages that - are considered lost in transit. + Optional, but recommended for DTLS 1.2 and required for DTLS 1.3. This + callback is used to schedule a deferred operation to be invoked after a + specified number of milliseconds. This is used by DTLS to schedule + retransmissions of handshake messages that are considered lost in transit. If this is not used, the application must call ``Channel::timeout_check()`` - independently and regularly whenever a DTLS handshake is in progress. In - contrast, if it is implemented by the application, make sure to never call + independently and regularly whenever a DTLS 1.2 handshake is in progress. + DTLS 1.3 cannot work without this callback. In contrast, if it is + implemented by the application, make sure to never call ``Channel::timeout_check()`` directly. The TLS implementation is not re-entrant. The ``op`` must be invoked in a @@ -230,7 +232,9 @@ additional information about the connection. Invoking ``op`` might throw an exception. Typically this indicates that the maximum number of retransmission attempts has been reached (see also - ``Policy::dtls_maximum_retransmissions()``) and the association is being + ``Policy::dtls_maximum_retransmissions()``), or that the interaction did + not make progress within the flight timeout (see also + ``Policy::dtls_flight_timeout()``), and the association is being abandoned. During an invocation of ``op`` the DTLS implementation might call @@ -312,13 +316,15 @@ available: Returns the remaining time until a call to ``timeout_check`` might retransmit DTLS handshake data. A zero duration means that a retransmission is due. If ``std::nullopt`` is returned, no timeout check - is currently needed. + is currently needed. For DTLS 1.3, this reports the deadlines of the + internal timers (retransmissions, ACK, flight timeout). .. note:: This method is deprecated and will be removed in Botan 4. - For DTLS 1.3 this will always return std::nullopt because a call to - ``timeout_check`` won't work for it anyway. + DTLS 1.3 handles its timers exclusively via + ``Callbacks::tls_register_deferred_operation``; calling + ``timeout_check`` on a DTLS 1.3 channel will throw. .. cpp:function:: bool is_closed() @@ -339,7 +345,7 @@ available: .. cpp:function:: bool timeout_check() - This function does nothing unless the channel represents a DTLS + This function does nothing unless the channel represents a DTLS 1.2 connection with a handshake in progress. Returns true if a timeout condition occurred and handshake packets were retransmitted. @@ -384,6 +390,10 @@ available: the same key. Applications only need to call this method to force a key update at a specific point in time. + On a DTLS 1.3 channel, this method might throw ``Invalid_State`` when + there is a pending key update that was not acknowledged by the peer yet. + In that case, the application should retry the request after some time. + Note that this is a TLS 1.3 feature and invocations on a channel using TLS 1.2 will throw. @@ -522,21 +532,40 @@ TLS Servers size_t reserved_io_buffer_size = 16*1024 \ ) -The first 5 arguments as well as the final argument -*reserved_io_buffer_size*, are treated similarly to the :ref:`client -`. + The first 5 arguments as well as the final argument + *reserved_io_buffer_size*, are treated similarly to the :ref:`client + `. + + If a client sends the ALPN extension, the ``callbacks`` function + ``tls_server_choose_app_protocol`` will be called and the result + sent back to the client. If the empty string is returned, the server + will not send an ALPN response. The function can also throw an exception + to abort the handshake entirely, the ALPN specification says that if this + occurs the alert should be of type `NO_APPLICATION_PROTOCOL`. + + The optional argument *is_datagram* specifies if this is a TLS or DTLS + server; unlike clients, which know what type of protocol (TLS vs DTLS) + they are negotiating from the start via the *offer_version*, servers + would not until they actually received a client hello. + + .. cpp:function:: size_t send_new_session_tickets(size_t tickets) + + Allows sending new session tickets to the client at any time after the + handshake has completed. The *tickets* parameter specifies how many + tickets to send. The return value is the number of tickets actually sent. + + Note that this is supported on (D)TLS 1.3 channels only, other channels + will always return 0. See also ``new_session_ticket_supported()`` -If a client sends the ALPN extension, the ``callbacks`` function -``tls_server_choose_app_protocol`` will be called and the result -sent back to the client. If the empty string is returned, the server -will not send an ALPN response. The function can also throw an exception -to abort the handshake entirely, the ALPN specification says that if this -occurs the alert should be of type `NO_APPLICATION_PROTOCOL`. + On a DTLS 1.3 channel, this method might throw ``Invalid_State`` when + there is a pending key update that was not acknowledged by the peer yet. + In that case, the application should retry the request after some time. -The optional argument *is_datagram* specifies if this is a TLS or DTLS -server; unlike clients, which know what type of protocol (TLS vs DTLS) -they are negotiating from the start via the *offer_version*, servers -would not until they actually received a client hello. + .. cpp:function:: bool new_session_ticket_supported() const + + Returns true if the channel supports sending new session tickets to the + client. This is true for (D)TLS 1.3 servers whose client offered any + PSK-based key exchange methods. .. _tls_server_example: @@ -935,7 +964,8 @@ policy settings from a file. Return true if this version of the protocol is one that we are willing to negotiate. - Default: Accepts TLS v1.2 and DTLS v1.2, and rejects all older versions. + Default: Accepts TLS v1.2/v1.3 and DTLS v1.2/DTLS v1.3 (experimental), and + rejects all older versions. .. cpp:function:: bool server_uses_own_ciphersuite_preferences() const @@ -1026,6 +1056,14 @@ policy settings from a file. Return true from here to allow TLS v1.3. Returns ``true`` by default. + .. cpp:function:: bool allow_dtls12() const + + Return true from here to allow DTLS v1.2. Returns ``true`` by default. + + .. cpp:function:: bool allow_dtls13() const + + Return true from here to allow DTLS v1.3. Returns ``true`` by default. + .. cpp:function:: size_t minimum_rsa_bits() const Minimum accepted RSA key size. Default 2048 bits. @@ -1207,7 +1245,8 @@ The ``TLS::Protocol_Version`` class represents a specific version: .. cpp:enum:: Version_Code - ``TLS_V10``, ``TLS_V11``, ``TLS_V12``, ``DTLS_V10``, ``DTLS_V12`` + ``TLS_V10``, ``TLS_V11``, ``TLS_V12``, ``TLS_V13``, ``DTLS_V10``, + ``DTLS_V12``, ``DTLS_V13`` .. cpp:function:: Protocol_Version(Version_Code named_version) @@ -1224,17 +1263,17 @@ The ``TLS::Protocol_Version`` class represents a specific version: .. cpp:function:: std::string to_string() const Returns string description of the version, for instance "TLS - v1.1" or "DTLS v1.0". + v1.3" or "DTLS v1.2". .. cpp:function:: static Protocol_Version latest_tls_version() Returns the latest version of the TLS protocol known to the library - (currently TLS v1.2) + (currently TLS v1.3) .. cpp:function:: static Protocol_Version latest_dtls_version() Returns the latest version of the DTLS protocol known to the - library (currently DTLS v1.2) + library (currently DTLS v1.2, or experimental DTLS v1.3) Post-quantum-secure key exchange diff --git a/doc/credits.rst b/doc/credits.rst index e472f072b23..c54df6bf8bf 100644 --- a/doc/credits.rst +++ b/doc/credits.rst @@ -163,7 +163,7 @@ snail-mail address (S), and Bitcoin address (B). N: Amos Treiber E: amos.treiber@rohde-schwarz.com W: https://www.rohde-schwarz.com/cybersecurity - D: SLH-DSA, TPM 2.0, FrodoKEM, Classic McEliece, ML-KEM, ML-DSA + D: SLH-DSA, TPM 2.0, FrodoKEM, Classic McEliece, ML-KEM, ML-DSA, DTLS 1.3 S: Cologne, Germany N: Daniel Seither @@ -179,7 +179,7 @@ snail-mail address (S), and Bitcoin address (B). N: René Meusel E: rene.meusel@rohde-schwarz.com W: https://www.rohde-schwarz.com/cybersecurity - D: TLS 1.3, ML-KEM, ML-DSA, SLH-DSA, FrodoKEM, TPM 2.0, CI + D: (D)TLS 1.3, ML-KEM, ML-DSA, SLH-DSA, FrodoKEM, TPM 2.0, CI S: Berlin, Germany N: Daniel Neus diff --git a/readme.rst b/readme.rst index c363bda845c..71366926f05 100644 --- a/readme.rst +++ b/readme.rst @@ -93,12 +93,12 @@ Find Enclosed Transport Layer Security (TLS) Protocol ---------------------------------------- -* TLS v1.2/v1.3, and DTLS v1.2 +* TLS v1.2/v1.3, DTLS v1.2, and DTLS v1.3 (experimental) * Supported extensions include session tickets, SNI, ALPN, OCSP stapling, encrypt-then-mac CBC, and extended master secret. * Supports authentication using certificates or preshared keys (PSK) * Supports record encryption with modern AEAD modes as well as legacy CBC ciphersuites. -* TLS 1.3 supports hybrid post-quantum key exchange using ML-KEM or FrodoKEM +* (D)TLS 1.3 supports hybrid post-quantum key exchange using ML-KEM or FrodoKEM Public Key Infrastructure ---------------------------------------- diff --git a/src/bogo_shim/bogo_shim.cpp b/src/bogo_shim/bogo_shim.cpp index 199dc819c54..b1a0c04bbd5 100644 --- a/src/bogo_shim/bogo_shim.cpp +++ b/src/bogo_shim/bogo_shim.cpp @@ -28,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -129,6 +130,7 @@ std::string map_to_bogo_error(const std::string& e, std::string_view test_name) } static const std::unordered_map err_map{ + {"ACK record refers to an invalid record number", ":DECODE_ERROR:"}, {"Application data before handshake done", ":APPLICATION_DATA_INSTEAD_OF_HANDSHAKE:"}, {"Bad Hello_Request, has non-zero size", ":BAD_HELLO_REQUEST:"}, {"Bad code for TLS alert level", ":UNKNOWN_ALERT_TYPE:"}, @@ -150,6 +152,7 @@ std::string map_to_bogo_error(const std::string& e, std::string_view test_name) {"Certificate usage constraints do not allow signing", ":KEY_USAGE_BIT_INCORRECT:"}, {"Can't agree on a ciphersuite with client", ":NO_SHARED_CIPHER:"}, {"Can't interleave application and handshake data", ":UNEXPECTED_RECORD:"}, + {"Cannot update keys: maximum DTLS epoch number reached", ":TOO_MANY_KEY_UPDATES:"}, {"Unexpected new DTLS handshake message", ":UNEXPECTED_RECORD:"}, {"Certificate chain exceeds policy specified maximum size", ":EXCESSIVE_MESSAGE_SIZE:"}, {"Certificate key type did not match ciphersuite", ":WRONG_CERTIFICATE_TYPE:"}, @@ -184,6 +187,8 @@ std::string map_to_bogo_error(const std::string& e, std::string_view test_name) {"No shared TLS version based on supported versions extension", ":UNSUPPORTED_PROTOCOL:"}, {"Client: No certificates sent by server", ":DECODE_ERROR:"}, {"Decoded polynomial coefficients out of range", ":BAD_ECPOINT:"}, + {"Deprotected DTLS record had unexpected content type: 42", ":UNEXPECTED_RECORD:"}, + {"Received DTLSPlaintext with unexpected content type: 23", ":UNEXPECTED_RECORD:"}, {"Non-PSK Client Hello did not contain supported_groups and signature_algorithms extensions", ":NO_SHARED_GROUP:"}, {"No certificates sent by server", ":PEER_DID_NOT_RETURN_A_CERTIFICATE:"}, @@ -192,6 +197,8 @@ std::string map_to_bogo_error(const std::string& e, std::string_view test_name) {"Counterparty sent inconsistent key and sig types", ":WRONG_SIGNATURE_TYPE:"}, {"Downgrade attack detected", ":TLS13_DOWNGRADE:"}, {"DTLS handshake timed out: maximum retransmissions exceeded", ":READ_TIMEOUT_EXPIRED:"}, + {"DTLS (post-)handshake message exchange timed out: flight timeout exceeded", ":READ_TIMEOUT_EXPIRED:"}, + {"DTLS (post-)handshake message exchange timed out: maximum retransmissions exceeded", ":READ_TIMEOUT_EXPIRED:"}, {"Empty ALPN protocol not allowed", ":PARSE_TLSEXT:"}, {"Empty PSK binders list", ":DECODE_ERROR: "}, {"Encoding error: Cannot encode PSS string, output length too small", ":NO_COMMON_SIGNATURE_ALGORITHMS:"}, @@ -258,9 +265,11 @@ std::string map_to_bogo_error(const std::string& e, std::string_view test_name) {"received an illegal handshake message", ":UNEXPECTED_MESSAGE:"}, {"Received a legacy Client Hello", ":UNSUPPORTED_PROTOCOL:"}, {"Received an unsupported Client Hello", ":UNSUPPORTED_PROTOCOL:"}, + {"Received an unexpected Hello Verify Request", ":UNSUPPORTED_PROTOCOL:"}, {"Received an unexpected legacy Server Hello", ":UNSUPPORTED_PROTOCOL:"}, {"Received an unsupported Server Hello", ":UNSUPPORTED_PROTOCOL:"}, {"Received application data after connection closure", ":APPLICATION_DATA_ON_SHUTDOWN:"}, + {"Received DTLSPlaintext with empty payload", ":UNEXPECTED_RECORD:"}, {"Received handshake data after connection closure", ":NO_RENEGOTIATION:"}, {"Received multiple key share entries for the same group", ":DUPLICATE_KEY_SHARE:"}, {"Received unexpected record version in initial record", ":WRONG_VERSION_NUMBER:"}, @@ -277,6 +286,7 @@ std::string map_to_bogo_error(const std::string& e, std::string_view test_name) {"Server replied with an invalid version", ":UNSUPPORTED_PROTOCOL:"}, {"server changed its chosen ciphersuite", ":WRONG_CIPHER_RETURNED:"}, {"Server replied with DTLS-SRTP alg we did not send", ":BAD_SRTP_PROTECTION_PROFILE_LIST:"}, + {"Server replied with DTLS-SRTP profile we did not offer", ":BAD_SRTP_PROTECTION_PROFILE_LIST:"}, {"Server replied with ciphersuite we didn't send", ":WRONG_CIPHER_RETURNED:"}, {"Server replied with an invalid version", ":UNSUPPORTED_PROTOCOL:"}, // bogus version from "ServerBogusVersion" {"Server version SSL v3 is unacceptable by policy", ":UNSUPPORTED_PROTOCOL:"}, // "NoSSL3-Client-Unsolicited" @@ -301,6 +311,7 @@ std::string map_to_bogo_error(const std::string& e, std::string_view test_name) {"Server selected a key exchange group we didn't offer.", ":WRONG_CURVE:"}, {"TLS 1.3 Server Hello selected a different version", ":SECOND_SERVERHELLO_VERSION_MISMATCH:"}, {"TLS signature extension did not allow for RSA_PSS_SHA256 signature", ":WRONG_SIGNATURE_TYPE:"}, + {"Truncated DTLS handshake fragment received", ":BAD_HANDSHAKE_RECORD:"}, {"Version downgrade received after Hello Retry", ":SECOND_SERVERHELLO_VERSION_MISMATCH:"}, {"Server sent an unsupported extension", ":UNEXPECTED_EXTENSION:"}, {"Unsupported extension found in Server Hello", ":UNEXPECTED_EXTENSION:"}, @@ -968,6 +979,7 @@ std::unique_ptr parse_options(char* argv[]) { "is-handshaker-supported", //"jdk11-workaround", "key-update", + "key-update-before-read", "no-key-shares", "new-psk-credential", "new-rpk-credential", @@ -1287,24 +1299,26 @@ class Shim_Policy final : public Botan::TLS::Policy { } // Default: offer key shares for the first classical group and the - // first post-quantum group, matching BoringSSL's default heuristic. + // first post-quantum group, matching BoringSSL's default heuristic. In + // DTLS, BoringSSL does not pre-offer post-quantum shares, so neither + // do we. std::vector to_offer; - bool have_classical = false; - bool have_pq = false; + bool need_classical = true; + bool need_pq = !m_args.flag_set("dtls"); for(const auto g : groups) { if(g.is_post_quantum()) { - if(!have_pq) { + if(need_pq) { to_offer.push_back(g); - have_pq = true; + need_pq = false; } } else { - if(!have_classical) { + if(need_classical) { to_offer.push_back(g); - have_classical = true; + need_classical = false; } } - if(have_classical && have_pq) { + if(!need_classical && !need_pq) { break; } } @@ -1422,6 +1436,11 @@ class Shim_Policy final : public Botan::TLS::Policy { allow_version(Botan::TLS::Protocol_Version::DTLS_V12); } + bool allow_dtls13() const override { + return m_args.flag_set("dtls") && !m_args.flag_set("no-tls13") && + allow_version(Botan::TLS::Protocol_Version::DTLS_V13); + } + //Botan::TLS::Group_Params default_dh_group() const override; //size_t minimum_dh_group_size() const override; @@ -1441,7 +1460,7 @@ class Shim_Policy final : public Botan::TLS::Policy { //std::chrono::seconds session_ticket_lifetime() const override; size_t new_session_tickets_upon_handshake_success() const override { - return m_args.flag_set("no-ticket") ? 0 : 1; + return m_args.flag_set("no-ticket") ? 0 : 2; // BoGo expects 2 tickets to be issued on handshake success } std::vector srtp_profiles() const override { @@ -1493,6 +1512,13 @@ class Shim_Policy final : public Botan::TLS::Policy { return m_args.get_int_opt_or_else("initial-timeout-duration-ms", 400); } + // BoGo's DTLS-Retransmit tests expect no timer to be armed once a flight + // was acknowledged (explicitly or implicitly). They are unaware of (and + // would trip over) a blanket flight timeout, so disable ours entirely. + std::optional dtls_flight_timeout() const override { return std::nullopt; } + + bool dtls_server_require_cookie_exchange() const override { return false; } + bool abort_connection_on_undesired_renegotiation() const override { return !m_args.flag_set("renegotiate-ignore"); } @@ -1755,7 +1781,9 @@ class Shim_Credentials final : public Botan::Credentials_Manager { std::vector psks; #if defined(BOTAN_HAS_TLS_13) // TLS 1.3 PSK credentials from -new-psk-credential blocks - const Botan::TLS::Protocol_Version target_version(Botan::TLS::Protocol_Version::TLS_V13); + const Botan::TLS::Protocol_Version target_version(m_args.flag_set("dtls") // + ? Botan::TLS::Protocol_Version::DTLS_V13 // + : Botan::TLS::Protocol_Version::TLS_V13); bool any_psk_block = false; for(const auto& cred : m_credentials) { @@ -1902,6 +1930,7 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { m_sessions_established(0), m_got_close(false), m_hello_retry_request(false), + m_key_update_before_read(args.flag_set("key-update-before-read") ? std::make_optional(true) : std::nullopt), m_clock_skew(0) {} size_t sessions_established() const { return m_sessions_established; } @@ -1912,6 +1941,13 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { bool saw_close_notify() const { return m_got_close; } + bool key_update_before_read_pending() const { return m_key_update_before_read.value_or(false); } + + void key_update_before_read_sent() { + BOTAN_STATE_CHECK(m_key_update_before_read.has_value()); + m_key_update_before_read = false; + } + void tls_emit_data(std::span data) override { shim_log("sending record of len " + std::to_string(data.size())); @@ -1961,6 +1997,11 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { } m_channel->send(buf); + + // The next read must be preceded by another KeyUpdate + if(m_key_update_before_read.has_value()) { + m_key_update_before_read = true; + } } bool tls_verify_message(const Botan::Public_Key& key, @@ -2336,6 +2377,8 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { // ACK, never from this callback (also not for a zero delay). void tls_register_deferred_operation(uint64_t monotonic_delay_ms, std::function op) override { const uint64_t deadline_ms = tls_current_monotonic_clock_ms() + monotonic_delay_ms; + shim_log("Registered a deferred operation in " + std::to_string(monotonic_delay_ms) + "ms (deadline " + + std::to_string(deadline_ms) + "ms)"); m_deferred_operations.emplace_back(Deferred_Operation{deadline_ms, std::move(op)}); } @@ -2347,7 +2390,8 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { // bit early makes the retransmission happen. void fire_due_deferred_operations() { const uint64_t now_ms = tls_current_monotonic_clock_ms(); - const uint64_t fudge_ms = std::min(15, m_policy.dtls_initial_timeout() / 2); + const uint64_t fudge_ms = + std::min(Botan::TLS::DTLS_RETRANSMISSION_TIMER_FUDGE, m_policy.dtls_initial_timeout() / 2); std::stable_sort(m_deferred_operations.begin(), m_deferred_operations.end()); @@ -2355,8 +2399,10 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { // Pop the operation from the queue only, then invoke it. op() might // throw an exception or register new deferred operations. Both of // which must happen only after m_deferred_operations got updated. + const auto deadline_ms = m_deferred_operations.front().deadline_ms; const auto op = std::move(m_deferred_operations.front().op); m_deferred_operations.erase(m_deferred_operations.begin()); + shim_log("Fired a deferred operation scheduled with deadline: " + std::to_string(deadline_ms) + "ms"); op(); } } @@ -2576,6 +2622,7 @@ class Shim_Callbacks final : public Botan::TLS::Callbacks { size_t m_sessions_established; bool m_got_close; bool m_hello_retry_request; + std::optional m_key_update_before_read; std::chrono::seconds m_clock_skew; // Virtual clock for the DTLS retransmit timer. Tracked in nanoseconds // (BoGo's wire unit) to avoid rounding errors @@ -2683,6 +2730,16 @@ int main(int /*argc*/, char* argv[]) { std::vector buf(buf_size); for(;;) { + if(callbacks->key_update_before_read_pending() && chan->is_handshake_complete()) { + shim_log("Updating traffic keys before read"); + try { + chan->update_traffic_keys(false /* don't request reciprocal update */); + } catch(const Botan::Invalid_State&) { + shim_log("Traffic key update rejected because another KeyUpdate is in progress"); + } + callbacks->key_update_before_read_sent(); + } + if(is_datagram) { uint8_t opcode = 0; const size_t got = socket.read(&opcode, 1); diff --git a/src/bogo_shim/config.json b/src/bogo_shim/config.json index 60daf31e8f6..57ef8673dbb 100644 --- a/src/bogo_shim/config.json +++ b/src/bogo_shim/config.json @@ -13,6 +13,7 @@ "EncryptedExtensionsWithKeyShare-TLS13": "expects 'unsupported extension' but RFC requires 'illegal parameter'", "ClientSkipCertificateVerify-TLS13": "would require ambiguous error mapping", "Resume-Client-Mismatch-TLS13-TLS12-TLS": "server requests a downgrade to TLS 1.2, echoing the random session ID during a TLS 1.3 resumption. => error mapping conflict", + "Resume-Client-Mismatch-TLS13-TLS12-DTLS": "server requests a downgrade to TLS 1.2, echoing the random session ID during a TLS 1.3 resumption. => error mapping conflict", "ServerAuth-NoFallback-TLS13": "would require ambiguous error mapping", "CertificateVerificationFail-Server-TLS12-TLS-Sync": "too picky TLS alert", "CertificateVerificationFail-Server-TLS12-CustomCallback-TLS-Sync": "too picky TLS alert", @@ -55,13 +56,18 @@ "GarbageCertificate-Server-TLS13": "too picky TLS alert", "AppDataBeforeTLS13KeyChange": "too picky TLS alert", "UnencryptedEncryptedExtensions": "Botan sends unexpected_message alert, BoGo expects bad_record_mac", + "UnencryptedEncryptedExtensions-DTLS": "Botan ignores all unencrypted handshake messages after key material was established, BoGo expects unexpected_message", "TrustAnchors-Unsolicited-Certificate": "Botan sends illegal_parameter alert, BoGo expects unsupported_extension", "Resume-Server-OmitAllPSKsOnSecondClientHello": "Botan allows the second ClientHello to drop all PSKs (RFC 8446 4.1.2), BoGo expects missing_extension", "PSK-Server-OmitAllPSKsOnSecondClientHello-TLS": "Botan allows the second ClientHello to drop all PSKs (RFC 8446 4.1.2), BoGo expects missing_extension", + "PSK-Server-OmitAllPSKsOnSecondClientHello-DTLS": "Botan allows the second ClientHello to drop all PSKs (RFC 8446 4.1.2), BoGo expects missing_extension", "PSK-Server-HRR-PSKMissing-TLS": "Botan sends handshake_failure alert, BoGo expects illegal_parameter", + "PSK-Server-HRR-PSKMissing-DTLS": "Botan sends handshake_failure alert, BoGo expects illegal_parameter", "PSK-Server-MissingPSKMode-NoMatch-TLS": "Botan reports PSK_IDENTITY_NOT_FOUND, BoGo expects NO_SUPPORTED_PSK_MODE", + "PSK-Server-MissingPSKMode-NoMatch-DTLS": "Botan reports PSK_IDENTITY_NOT_FOUND, BoGo expects NO_SUPPORTED_PSK_MODE", "ExtensionTrailingData-ServerName-Client-TLS-TLS12": "Botan sends illegal_parameter for malformed server SNI; BoGo expects decode_error", "ExtensionTrailingData-ServerName-Client-TLS-TLS13": "Botan sends illegal_parameter for malformed server SNI; BoGo expects decode_error", + "ExtensionTrailingData-ServerName-Client-DTLS-TLS13": "Botan sends illegal_parameter for malformed server SNI; BoGo expects decode_error", "ExtensionTrailingData-ServerName-Client-DTLS-TLS12": "Botan sends illegal_parameter for malformed server SNI; BoGo expects decode_error", "ClientCertificateType-Server-RejectsInvalidEmptyExtension-VerifyPeer-TLS13": "Botan sends decode_error, BoGo expects illegal_parameter", "ClientCertificateType-Server-RejectsInvalidEmptyExtension-FailIfNoClientCert-TLS13": "Botan sends decode_error, BoGo expects illegal_parameter", @@ -76,7 +82,24 @@ "TrailingDataWithFinished-Client-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", "TrailingDataWithFinished-Resume-Client-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", "TrailingDataWithFinished-Server-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", - "TrailingDataWithFinished-Resume-Server-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)" + "TrailingDataWithFinished-Resume-Server-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", + "DTLS13-HelloVerifyRequest-DTLS-Sync": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Sync": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Sync-ImplicitHandshake": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequest-DTLS-Sync-ImplicitHandshake": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequest-DTLS-Sync-SplitHandshakeRecords": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Sync-SplitHandshakeRecords": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequest-DTLS-Sync-PackHandshake": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Sync-PackHandshake": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Async": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequest-DTLS-Async": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequest-DTLS-Async-ImplicitHandshake": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Async-ImplicitHandshake": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequest-DTLS-Async-SplitHandshakeRecords": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Async-SplitHandshakeRecords": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Async-PackHandshake": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-HelloVerifyRequest-DTLS-Async-PackHandshake": "Botan downgrades on HVR and then rejects the DTLS 1.3 messages with a different error", + "DTLS13-RejectLegacyCookie": "Botan follows RFC 9147 5.3 and aborts with an illegal_parameter alert, BoGo expects decode_error" }, "DisabledTests": { "*ML-DSA*": "Need support for the LAMPS tagged seed keys", @@ -89,12 +112,6 @@ "*TLS11": "No TLS 1.1", "*-TLS11-*": "No TLS 1.1", "TLS11-*": "No TLS 1.1", - "*DTLS13*": "No DTLS 1.3", - "DTLS-TLS13*": "No DTLS 1.3", - "*TLS13-DTLS": "No DTLS 1.3", - "*DTLS-TLS13": "No DTLS 1.3", - "TLS13*-DTLS-*": "No DTLS 1.3", - "MinimumVersion-*-TLS13-*DTLS": "No DTLS 1.3", "*RSA_PKCS1_MD5_SHA1": "We do not implement MD5/SHA1 concatenation anyway", "*RSA_PKCS1_SHA1*": "We do not implement PKCS1 SHA-1", "*-ECDSA_SHA1-*": "We do not implement ECDSA SHA-1", @@ -116,7 +133,9 @@ "TLS12SessionID-TLS13": "We don't offer TLS 1.3 when a TLS 1.2 session was found", "Ticket-Forbidden-TLS13": "We don't offer TLS 1.3 when a TLS 1.2 session was found", "Resume-Client-NoResume-TLS12-TLS13-TLS": "We don't offer TLS 1.3 when a TLS 1.2 session was found", + "Resume-Client-NoResume-TLS12-TLS13-DTLS": "We don't offer TLS 1.3 when a TLS 1.2 session was found", "Resume-Client-Mismatch-TLS12-TLS13-TLS": "We don't offer TLS 1.3 when a TLS 1.2 session was found", + "Resume-Client-Mismatch-TLS12-TLS13-DTLS": "We don't offer TLS 1.3 when a TLS 1.2 session was found", "Resume-Server-UnofferedCipher-TLS13": "BoringSSL will not allow switching ciphers during TLS 1.3 resumption, we do, though.", "HttpGET": "TLS 1.3 server does not detect HTTP", "HttpPOST": "TLS 1.3 server does not detect HTTP", @@ -128,6 +147,11 @@ "EarlyDataEnabled*": "No TLS 1.3 Early Data, yet", "EarlyData-Reject0RTT*": "No TLS 1.3 Early Data, yet", "PartialEndOfEarlyDataWithClientHello": "No TLS 1.3 Early Data, yet", + "KeyUpdate-DeferredSend-DTLS": "Botan does not defer KeyUpdates on the client side until the entire handshake is fully ACKed", + "KeyUpdate-MaxWriteMessage-DTLS": "Test is very slow (because it runs through 2^16 key updates)", + "KeyUpdate-MaxWriteEpoch-DTLS": "Test is very slow (because it runs through 2^16 key updates)", + "KeyUpdate-WriteMessageOverflow-DTLS": "Test is very slow (because it runs through 2^16 key updates)", + "KeyUpdate-WriteEpochOverflow-DTLS": "Test is very slow (because it runs through 2^16 key updates)", "TLS-ECH*": "No ECH support", "DuplicateCertCompressionExt*": "No support for 1.3 cert compression extension", "CertCompression*-TLS13": "No support for 1.3 cert compression extension", @@ -196,9 +220,10 @@ "CurveTest-*-Compressed*": "Point compression is supported, which BoGo doesn't expect", "PointFormat-*-MissingUncompressed": "Point compression is supported, which BoGo doesn't expect", "SRTP-Server-IgnoreMKI-*": "Non-empty MKI is rejected (bug)", - "DTLS-Retransmit-*-TLS13*": "No DTLS 1.3 support", - "DTLS-Retransmit-PartialProgress-*-TLS13*": "No DTLS 1.3 support", - "DTLS-Retransmit-Server-*": "Expects a timer-driven HelloVerifyRequest retransmit; RFC 6347 3.2.1 says timeout and retransmission do not apply to HelloVerifyRequest", + "DTLS-Retransmit-BothTimers-TLS13*": "Botan's DTLS does not ACK previously seen messages (the 'BothTimers' test exercises some BoringSSL-internal implementation detail)", + "DTLS-Retransmit-Server-*TLS12*": "Expects a timer-driven HelloVerifyRequest retransmit; RFC 6347 3.2.1 says timeout and retransmission do not apply to HelloVerifyRequest", + "DTLS-Retransmit-Server-ACKForwards-TLS13*": "Retransmissions in Botan don't re-pack the datagram after ACKs", + "DTLS-Retransmit-Server-ACKIterate-TLS13*": "No API to change the MTU on an existing channel", "DTLS-Retransmit-*SetTimeout*": "No API to change the retransmit timer mid-handshake", "DTLS-Retransmit-ChangeMTU*": "No API to change the MTU on an existing channel", "TLS-HintMismatch-*": "BoringSSL specific handshake hints (split handshakes)", @@ -206,16 +231,7 @@ "ALPNClient-AllowUnknown-*": "Botan always validates server ALPN selection against offered list", "SendEmptySessionTicket-TLS13": "Botan sends internal_error instead of decode_error - empty ticket is caught later than the spec expects", "DTLS-ECH*": "No ECH support", - "KeyUpdate-*-DTLS": "No DTLS 1.3", - "AppDataBeforeTLS13KeyChange-DTLS*": "No DTLS 1.3", - "UnencryptedEncryptedExtensions-DTLS": "No DTLS 1.3", - "TLS13-OnlyPadding-DTLS": "No DTLS 1.3", - "Resume-*-TLS13-TLS12-DTLS": "No DTLS 1.3", - "Downgrade-TLS12-*-DTLS": "No DTLS 1.3", - "WrongMessageType-TLS13-*-DTLS": "No DTLS 1.3", - "TrailingMessageData-TLS13-EncryptedExtensions-DTLS": "No DTLS 1.3", - "TrailingMessageData-TLS13-ServerCertificateVerify-DTLS": "No DTLS 1.3", - "KeyChangeWithBufferedMessages-DTLS": "No DTLS 1.3", + "KeyChangeWithBufferedMessages-DTLS": "DTLS 1.2, needs investigation", "Renegotiate-DTLS-Server-Forbidden": "Botan tolerates DTLS renegotiation", "Renegotiate-DTLS-Client-Forbidden": "Botan tolerates DTLS renegotiation", "RejectPSSKeyType-*": "Botan does not reject RSA-PSS key type", @@ -251,7 +267,6 @@ "ClientCertificateType-Client-OffersX509RPK-SendsRequestedX509-TLS13": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", "ClientCertificateType-Client-Explicit-*-SendsRequested*-TLS13*": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", "ClientCertificateType-Client-Explicit-OffersRPK-NotActuallyConfigured-ServerRequestsRPK-TLS13*": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", - "TLS13-EmptyRecords-DTLS": "No DTLS 1.3", "Client-Sign-RSA_PKCS1_SHA256_LEGACY-TLS12": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", "Client-SignDefault-RSA_PKCS1_SHA256_LEGACY-TLS12": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", "Client-Sign-RSA_PKCS1_SHA256-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", @@ -261,7 +276,6 @@ "Client-Sign-RSA_PKCS1_SHA512-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", "Client-SignDefault-RSA_PKCS1_SHA512-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", "SendInvalidRecordType-DTLS": "Botan silently discards DTLS records of an unknown type (RFC 6347 4.1.2.7)", - "TLS13-RecordPadding-DTLS": "No DTLS 1.3", "ClientCertificateType-Server-*-TLS12": "Botan does not support RPK certificate type negotiation in TLS 1.2", "ClientCertificateType-Client-*-TLS12*": "Botan does not support RPK certificate type negotiation in TLS 1.2", "ServerCertificateType-Server-*-TLS12*": "Botan does not support RPK certificate type negotiation in TLS 1.2", @@ -276,9 +290,10 @@ "ServerCertificateType-Client-RequestsRPKOnly-ServerPickedX509ByDefaultInError-TLS13": "Botan does not enforce client-side cert type rejection of unsolicited X509", "ExtensionTrailingData-TrustAnchors-ClientHello-Server-TLS-TLS13": "No TrustAnchors extension support", "PSK-Server-DoNotRequestClientCertificate-TLS": "Botan declines external PSKs when client certificates are required", - "PSK-Client-PSKRequired-TLS": "Botan client does not enforce PSK-only mode", - "PSK-Client-PSKRequired-TLS12-TLS": "Botan client does not enforce PSK-only mode", - "PSK-*-DTLS": "No DTLS 1.3", + "PSK-Server-DoNotRequestClientCertificate-DTLS": "Botan declines external PSKs when client certificates are required", + "ExtensionTrailingData-TrustAnchors-ClientHello-Server-DTLS-TLS13": "No TrustAnchors extension support", + "PSK-Client-PSKRequired-*TLS": "Botan client does not enforce PSK-only mode", + "PSK-Client-PSKRequired-TLS12-*TLS": "Botan client does not enforce PSK-only mode", "DTLS-Replay-NonMonotonic*": "Needs investigation, started failing after https://github.com/google/boringssl/commit/f94f3ed3965ea033001fb9ae006084eee408b861", "AlternateEmptyRecordsAndWarningAlerts": "Botan has a single limit on consecutive empty records and warning alerts combined", "CredentialSessionIDContext-*": "Botan has no session ID context to restrict which sessions may be resumed", @@ -307,7 +322,9 @@ "CurveID-Resume-Server": "Botan does not record the key exchange group of a TLS 1.2 session, so cannot report it on resumption", "ClientCertificateTypes": "Botan ignores CertificateRequest certificate types it does not support, so cannot report them all", "SkipCertificateStatus*": "Checks BoringSSL's message callback trace, which Botan has no equivalent of", - "TLS13-CipherPreference-*": "Botan's cipher suite preference does not depend on whether AES is hardware accelerated" + "TLS13-CipherPreference-*": "Botan's cipher suite preference does not depend on whether AES is hardware accelerated", + "DTLS13CompatibilityMode-EchoSessionID": "This test is causing a downgrade to TLS 1.2 and only then it mirrors the sessionID", + "DTLS13CompatibilityMode-EchoSessionID-HelloRetryRequest": "The client resumes the DTLS 1.2 session with DTLS 1.2 only, so the DTLS 1.3-only runner aborts before the session ID echo could be validated" }, "ErrorMap": { ":CLIENTHELLO_PARSE_FAILED:": [ diff --git a/src/bogo_shim/config_no_dtls13.json b/src/bogo_shim/config_no_dtls13.json new file mode 100644 index 00000000000..60daf31e8f6 --- /dev/null +++ b/src/bogo_shim/config_no_dtls13.json @@ -0,0 +1,324 @@ +{ + "LooseErrorTests": { + "AppDataBeforeHandshake": "BoGo expects different error before vs after CCS", + "AppDataBeforeHandshake-Empty": "Invalid record message", + "ServerHelloBogusCipher": "Unexpected error", + "Garbage": "Decoding error", + "Resume-Client-CipherMismatch": "Unexpected error", + "NoSharedCipher": "Unexpected error", + "NoSharedCipher-TLS13": "Unexpected error", + "PartialFinishedWithServerHelloDone": "Unexpected record vs excess handshake data", + "HelloRetryRequest-DuplicateCurve-TLS13": "expects 'illegal parameter' but we want to stick with 'decode error'", + "HelloRetryRequest-DuplicateCookie-TLS13": "expects 'illegal parameter' but we want to stick with 'decode error'", + "EncryptedExtensionsWithKeyShare-TLS13": "expects 'unsupported extension' but RFC requires 'illegal parameter'", + "ClientSkipCertificateVerify-TLS13": "would require ambiguous error mapping", + "Resume-Client-Mismatch-TLS13-TLS12-TLS": "server requests a downgrade to TLS 1.2, echoing the random session ID during a TLS 1.3 resumption. => error mapping conflict", + "ServerAuth-NoFallback-TLS13": "would require ambiguous error mapping", + "CertificateVerificationFail-Server-TLS12-TLS-Sync": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-CustomCallback-TLS-Sync": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-TLS-Sync-ImplicitHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-CustomCallback-TLS-Sync-ImplicitHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-TLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-CustomCallback-TLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-TLS-Sync-PackHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-CustomCallback-TLS-Sync-PackHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-DTLS-Sync": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-DTLS-Sync": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-CustomCallback-DTLS-Sync": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-CustomCallback-DTLS-Sync": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-DTLS-Sync-ImplicitHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-CustomCallback-DTLS-Sync-ImplicitHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-CustomCallback-DTLS-Sync-ImplicitHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-DTLS-Sync-ImplicitHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-CustomCallback-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-CustomCallback-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-CustomCallback-DTLS-Sync-PackHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS12-DTLS-Sync-PackHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-DTLS-Sync-PackHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-CustomCallback-DTLS-Sync-PackHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-TLS-Sync": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-CustomCallback-TLS-Sync": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-TLS-Sync-ImplicitHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-CustomCallback-TLS-Sync-ImplicitHandshake": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-TLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Server-TLS13-CustomCallback-TLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Client-TLS12-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Client-TLS12-CustomCallback-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Client-TLS13-CustomCallback-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "CertificateVerificationFail-Client-TLS13-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "ClientOCSPCallback-FailNoStaple-TLS12-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "ClientOCSPCallback-FailNoStaple-TLS13-DTLS-Sync-SplitHandshakeRecords": "too picky TLS alert", + "WrongMessageType-TLS13-ClientCertificate-TLS": "too picky TLS alert", + "TrailingMessageData-TLS13-ClientCertificate-TLS": "too picky TLS alert", + "GarbageCertificate-Server-TLS13": "too picky TLS alert", + "AppDataBeforeTLS13KeyChange": "too picky TLS alert", + "UnencryptedEncryptedExtensions": "Botan sends unexpected_message alert, BoGo expects bad_record_mac", + "TrustAnchors-Unsolicited-Certificate": "Botan sends illegal_parameter alert, BoGo expects unsupported_extension", + "Resume-Server-OmitAllPSKsOnSecondClientHello": "Botan allows the second ClientHello to drop all PSKs (RFC 8446 4.1.2), BoGo expects missing_extension", + "PSK-Server-OmitAllPSKsOnSecondClientHello-TLS": "Botan allows the second ClientHello to drop all PSKs (RFC 8446 4.1.2), BoGo expects missing_extension", + "PSK-Server-HRR-PSKMissing-TLS": "Botan sends handshake_failure alert, BoGo expects illegal_parameter", + "PSK-Server-MissingPSKMode-NoMatch-TLS": "Botan reports PSK_IDENTITY_NOT_FOUND, BoGo expects NO_SUPPORTED_PSK_MODE", + "ExtensionTrailingData-ServerName-Client-TLS-TLS12": "Botan sends illegal_parameter for malformed server SNI; BoGo expects decode_error", + "ExtensionTrailingData-ServerName-Client-TLS-TLS13": "Botan sends illegal_parameter for malformed server SNI; BoGo expects decode_error", + "ExtensionTrailingData-ServerName-Client-DTLS-TLS12": "Botan sends illegal_parameter for malformed server SNI; BoGo expects decode_error", + "ClientCertificateType-Server-RejectsInvalidEmptyExtension-VerifyPeer-TLS13": "Botan sends decode_error, BoGo expects illegal_parameter", + "ClientCertificateType-Server-RejectsInvalidEmptyExtension-FailIfNoClientCert-TLS13": "Botan sends decode_error, BoGo expects illegal_parameter", + "ClientCertificateType-Server-RejectsInvalidDefaultOnly-FailIfNoClientCert-TLS13": "Botan reports PEER_DID_NOT_RETURN_A_CERTIFICATE, BoGo expects DECODE_ERROR", + "ClientCertificateType-Server-NoClientHelloCertTypes-NoSharedType-FailIfNoClientCert-TLS13": "Botan reports PEER_DID_NOT_RETURN_A_CERTIFICATE, BoGo expects UNSUPPORTED_CERTIFICATE", + "ServerCertificateType-Client-RequestsRPKOnly-NegotiatedRPK-ServerIncorrectlySentX509-TLS13": "Botan parses RPK as X.509 and fails with BER decode error rather than DECODE_ERROR cleanly", + "ServerCertificateType-Client-RequestsRPKOnly-ServerSentEmptyRPK-TLS13": "Empty RPK rejected with generic ASN.1 error rather than INVALID_RAW_PUBLIC_KEY", + "ClientCertificateType-Server-RPKReceived-RPKAccepted-ClientSentX509InError-VerifyPeer-TLS13": "Botan parses RPK as X.509 and fails with BER decode error rather than DECODE_ERROR cleanly", + "ClientCertificateType-Server-RPKReceived-RPKAccepted-ClientSentX509InError-FailIfNoClientCert-TLS13": "Botan parses RPK as X.509 and fails with BER decode error rather than DECODE_ERROR cleanly", + "ClientCertificateType-Server-ClientSentEmptyRPK-TLS13": "Empty RPK rejected with generic ASN.1 error rather than INVALID_RAW_PUBLIC_KEY", + "AlternateEmptyRecordsAndTooManyWarningAlerts": "Botan has a single limit on consecutive empty records and warning alerts combined; it rejects the connection but reports TOO_MANY_EMPTY_FRAGMENTS", + "TrailingDataWithFinished-Client-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", + "TrailingDataWithFinished-Resume-Client-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", + "TrailingDataWithFinished-Server-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", + "TrailingDataWithFinished-Resume-Server-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)" + }, + "DisabledTests": { + "*ML-DSA*": "Need support for the LAMPS tagged seed keys", + "*MLDSA*": "No ML-DSA support in TLS, and Botan's TLS 1.2 messages do not filter out configured but unavailable signature schemes", + "*TLS1": "No TLS 1.0", + "*-TLS1-*": "No TLS 1.0", + "TLS1-*": "No TLS 1.0", + "VersionNegotiation*-TLS": "No TLS 1.0", + "VersionNegotiation*-DTLS": "No DTLS 1.0", + "*TLS11": "No TLS 1.1", + "*-TLS11-*": "No TLS 1.1", + "TLS11-*": "No TLS 1.1", + "*DTLS13*": "No DTLS 1.3", + "DTLS-TLS13*": "No DTLS 1.3", + "*TLS13-DTLS": "No DTLS 1.3", + "*DTLS-TLS13": "No DTLS 1.3", + "TLS13*-DTLS-*": "No DTLS 1.3", + "MinimumVersion-*-TLS13-*DTLS": "No DTLS 1.3", + "*RSA_PKCS1_MD5_SHA1": "We do not implement MD5/SHA1 concatenation anyway", + "*RSA_PKCS1_SHA1*": "We do not implement PKCS1 SHA-1", + "*-ECDSA_SHA1-*": "We do not implement ECDSA SHA-1", + "*RSA_PKCS1_SHA256_LEGACY-TLS13": "We do allow for PKCS1 in TLS 1.3", + "Compliance-fips-202205-*": "We do not have explicit support for a FIPS TLS policy", + "Compliance-fips-202609-*": "We do not have explicit support for a FIPS TLS policy", + "Compliance-cnsa1-202603-*": "We do not have explicit support for CNSA", + "Compliance-cnsa2-202603-*": "We do not have explicit support for CNSA", + "UnsupportedCipherSuite-TLS13": "Relies on the WPA Enterprise compliance policy to limit the client's cipher suites", + "Compliance-wpa-202304-*": "We do not have explicit support for the WPA Enterprise mode", + "Compliance-cnsa202407-*": "We do not have explicit support for CNSA", + "CBCRecordSplitting*": "No need to split CBC records in TLS 1.2", + "DelegatedCredentials*": "No support of -delegated-cerdential", + "*SCSV*": "SCSV is meaningless without TLS 1.0/1.1 support", + "AllExtensions-*": "Not all extensions are implemented", + "VersionTolerance-TLS13": "We are not tolerating 0x0400 as Client Hello legacy_version", + "Server-JDK11-*": "We don't implement JDK-specific workarounds", + "Client-RejectJDK11DowngradeRandom": "We don't implement this workaround", + "TLS12SessionID-TLS13": "We don't offer TLS 1.3 when a TLS 1.2 session was found", + "Ticket-Forbidden-TLS13": "We don't offer TLS 1.3 when a TLS 1.2 session was found", + "Resume-Client-NoResume-TLS12-TLS13-TLS": "We don't offer TLS 1.3 when a TLS 1.2 session was found", + "Resume-Client-Mismatch-TLS12-TLS13-TLS": "We don't offer TLS 1.3 when a TLS 1.2 session was found", + "Resume-Server-UnofferedCipher-TLS13": "BoringSSL will not allow switching ciphers during TLS 1.3 resumption, we do, though.", + "HttpGET": "TLS 1.3 server does not detect HTTP", + "HttpPOST": "TLS 1.3 server does not detect HTTP", + "HttpPUT": "TLS 1.3 server does not detect HTTP", + "HttpHEAD": "TLS 1.3 server does not detect HTTP", + "HttpCONNECT": "TLS 1.3 server does not detect HTTP", + "*EarlyData*": "No TLS 1.3 Early Data, yet", + "TLS13-TicketAgeSkew-*": "No TLS 1.3 Early Data, yet", + "EarlyDataEnabled*": "No TLS 1.3 Early Data, yet", + "EarlyData-Reject0RTT*": "No TLS 1.3 Early Data, yet", + "PartialEndOfEarlyDataWithClientHello": "No TLS 1.3 Early Data, yet", + "TLS-ECH*": "No ECH support", + "DuplicateCertCompressionExt*": "No support for 1.3 cert compression extension", + "CertCompression*-TLS13": "No support for 1.3 cert compression extension", + "SupportedVersionSelection-TLS12": "We just ignore the version extension in this case", + "CheckClientCertificateTypes": "Client certificate type check is a library-user responsibility", + "Agree-Digest-SHA1": "No SHA-1 in TLS 1.2", + "ServerAuth-SHA1-Fallback-*": "No SHA-1 in TLS 1.2", + "*-InvalidSignature-*_SHA1-TLS12": "No SHA-1 in TLS 1.2", + "*-Sign-*_SHA1-TLS12": "No SHA-1 in TLS 1.2", + "*-Sign-Negotiate-*_SHA1-TLS12": "No SHA-1 in TLS 1.2", + "*-VerifyDefault-*_SHA1-TLS12": "No SHA-1 in TLS 1.2", + "*-Verify-*_SHA1-TLS12": "No SHA-1 in TLS 1.2", + "*QUIC*": "No QUIC", + "ALPS*": "No ALPS", + "ExtraClientEncryptedExtension-*": "No ALPS", + "*NPN*": "No support for NPN", + "ALPNServer-Preferred-*": "No support for NPN", + "*-NextProtocol*": "No support for NPN", + "TooManyKeyUpdates": "BoringSSL's approach to KeyUpdate throttling is ineffective and pointless", + "*SignedCertificateTimestamp*": "No support for SCT", + "*SCT*": "No support for SCT", + "Renegotiation-ChangeAuthProperties": "No support for SCT", + "UnsolicitedCertificateExtensions-*": "No support for SCT", + "IgnoreExtensionsOnIntermediates-TLS13": "No support for SCT", + "CertificateVerificationSoftFail*": "Botan has no equivalent of SSL_VERIFY_NONE; a failed certificate verification always aborts the handshake", + "*GREASE*": "No support for GREASE", + "*ChannelID*": "No support for ChannelID", + "TLSUnique*": "Botan does not expose the tls-unique channel binding", + "*V2ClientHello*": "No support for SSLv2 client hellos", + "*Ed25519*": "Ed25519 not implemented in TLS", + "*FalseStart*": "Botan doesn't do false start", + "MaxSendFragment*": "Botan has no option to limit the size of the records it sends", + "ExportKeyingMaterial-EmptyContext*": "No support for empty context", + "Peek-*": "No peek API", + "*OldCallback*": "BoringSSL specific API test", + "*Renegotiate-Client-Explicit*": "BoringSSL specific API test", + "CBCRecordSplittingPartialWrite*": "BoringSSL specific API test", + "TicketCallback*": "BoringSSL specific API test", + "Server-DDoS*": "BoringSSL specific API test", + "RetainOnlySHA256-*": "BoringSSL specific API test", + "Renegotiate-Client-UnfinishedWrite": "BoringSSL specific API test", + "FailEarlyCallback": "BoringSSL specific API test", + "ShimTicketRewritable": "Botan has a different ticket format", + "Resume-Server-DeclineCrossVersion*": "Botan has a different ticket format", + "Resume-Server-DeclineBadCipher*": "Botan has a different ticket format", + "Resume-Server-CipherNotPreferred*": "Botan has a different ticket format", + "TLS*-NoTicket-NoAccept": "BoGo expects that if ticket is issued stateful resumption is impossible", + "CheckLeafCurve": "Botan doesn't care what curve an ECDSA cert uses", + "CheckECDSACurve-TLS12": "Botan doesn't care what curve an ECDSA cert uses", + "CertificateVerificationFailsOnResume*": "Botan has no option to verify the peer certificate again on resumption", + "CertificateVerificationPassesOnResume*": "Botan has no option to verify the peer certificate again on resumption", + "CipherNegotiation-2": "No support for cipher equivalence classes", + "CipherNegotiation-3": "No support for cipher equivalence classes", + "CipherNegotiation-4": "No support for cipher equivalence classes", + "CipherNegotiation-5": "No support for cipher equivalence classes", + "CipherNegotiation-8": "No support for cipher equivalence classes", + "ALPNServer-SelectEmpty-*": "Botan treats empty ALPN from callback as a decline", + "Resume-Client-NoResume-TLS1-TLS11-TLS": "BoGo expects resumption attempt sends latest version", + "Resume-Client-NoResume-TLS1-TLS12-TLS": "BoGo expects resumption attempt sends latest version", + "Resume-Client-NoResume-TLS11-TLS12-TLS": "BoGo expects resumption attempt sends latest version", + "Resume-Client-NoResume-TLS1-TLS12-DTLS": "BoGo expects resumption attempt sends latest version", + "Resume-Client-Mismatch-TLS1-TLS11-TLS": "BoGo expects resumption attempt sends latest version", + "Resume-Client-Mismatch-TLS1-TLS12-TLS": "BoGo expects resumption attempt sends latest version", + "Resume-Client-Mismatch-TLS11-TLS12-TLS": "BoGo expects resumption attempt sends latest version", + "Resume-Client-Mismatch-TLS1-TLS12-DTLS": "BoGo expects resumption attempt sends latest version", + "CurveTest-*-Compressed*": "Point compression is supported, which BoGo doesn't expect", + "PointFormat-*-MissingUncompressed": "Point compression is supported, which BoGo doesn't expect", + "SRTP-Server-IgnoreMKI-*": "Non-empty MKI is rejected (bug)", + "DTLS-Retransmit-*-TLS13*": "No DTLS 1.3 support", + "DTLS-Retransmit-PartialProgress-*-TLS13*": "No DTLS 1.3 support", + "DTLS-Retransmit-Server-*": "Expects a timer-driven HelloVerifyRequest retransmit; RFC 6347 3.2.1 says timeout and retransmission do not apply to HelloVerifyRequest", + "DTLS-Retransmit-*SetTimeout*": "No API to change the retransmit timer mid-handshake", + "DTLS-Retransmit-ChangeMTU*": "No API to change the MTU on an existing channel", + "TLS-HintMismatch-*": "BoringSSL specific handshake hints (split handshakes)", + "CertificateSelection-*": "Certificate selection is a library-user responsibility", + "ALPNClient-AllowUnknown-*": "Botan always validates server ALPN selection against offered list", + "SendEmptySessionTicket-TLS13": "Botan sends internal_error instead of decode_error - empty ticket is caught later than the spec expects", + "DTLS-ECH*": "No ECH support", + "KeyUpdate-*-DTLS": "No DTLS 1.3", + "AppDataBeforeTLS13KeyChange-DTLS*": "No DTLS 1.3", + "UnencryptedEncryptedExtensions-DTLS": "No DTLS 1.3", + "TLS13-OnlyPadding-DTLS": "No DTLS 1.3", + "Resume-*-TLS13-TLS12-DTLS": "No DTLS 1.3", + "Downgrade-TLS12-*-DTLS": "No DTLS 1.3", + "WrongMessageType-TLS13-*-DTLS": "No DTLS 1.3", + "TrailingMessageData-TLS13-EncryptedExtensions-DTLS": "No DTLS 1.3", + "TrailingMessageData-TLS13-ServerCertificateVerify-DTLS": "No DTLS 1.3", + "KeyChangeWithBufferedMessages-DTLS": "No DTLS 1.3", + "Renegotiate-DTLS-Server-Forbidden": "Botan tolerates DTLS renegotiation", + "Renegotiate-DTLS-Client-Forbidden": "Botan tolerates DTLS renegotiation", + "RejectPSSKeyType-*": "Botan does not reject RSA-PSS key type", + "CertificateCipherMismatch-PSS": "Botan does not reject PSS cipher mismatch", + "ServerNameExtensionServer-*-TLS12": "Botan does not echo server_name in TLS 1.2 ServerHello", + "IgnoreLegacyVersion-TLS13": "Botan strictly validates legacy_version in TLS 1.3 ClientHello", + "MTU-DTLS12-3DES-CBC": "No 3DES support", + "TLS13-Client-*TicketFlags": "Botan does not implement the TLS Flags extension, so has no ticket flags or resumption across names", + "TLS12-NoTicket-NoOffer": "Different session ticket/ID handling", + "PAKE-*": "No PAKE support", + "TrustAnchors-Empty-*": "No TrustAnchors extension support", + "TrustAnchors-TooLong-*": "No TrustAnchors extension support", + "TrustAnchors-NonMinimalComponent-*": "No TrustAnchors extension support", + "TrustAnchors-TruncatedComponent-*": "No TrustAnchors extension support", + "TrustAnchors-TrustAnchorNegotiationProperty": "No TrustAnchors extension support", + "TrustAnchorGroups-*": "No TrustAnchors extension support", + "TrustAnchors-ServerSelect-*": "No TrustAnchors extension support", + "TrustAnchors-ServerReceiveEmptyRequest": "No TrustAnchors extension support", + "TrustAnchors-TLS12-Server": "No TrustAnchors extension support, so credentials which must match the issuer are not skipped", + "TrustAnchors-NoTrustAnchorNegotiationProperty": "No TrustAnchors extension support", + "TrustAnchors-ClientRequest*": "No TrustAnchors extension support", + "TrustAnchors-TLS12-Client": "No TrustAnchors extension support", + "TrustAnchors-Server-OverrideAvailable*": "No TrustAnchors extension support", + "TrustAnchors-Server-FilterAvailable*": "No TrustAnchors extension support", + "ExtensionTrailingData-TrustAnchors-*-Client-*": "No TrustAnchors extension support", + "PSK-Server-CertOrPSK-Cert-*": "A Botan server always prefers a matching external PSK to certificate authentication", + "ClientCertificateType-Client-OffersRPKOnly-ServerOmitsExtension-TLS13": "Botan does not reject when server omits cert_type extension and client only offers RPK", + "ClientCertificateType-Client-OffersRPKOnly-SendsRequestedRPK-TLS13": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", + "ClientCertificateType-Client-OffersRPKX509-SendsRequestedRPK-TLS13": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", + "ClientCertificateType-Client-OffersRPKX509-SendsRequestedX509-TLS13": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", + "ClientCertificateType-Client-OffersMultipleRPKs-SendsFirstRPK-TLS13": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", + "ClientCertificateType-Client-OffersX509RPK-SendsRequestedRPK-TLS13": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", + "ClientCertificateType-Client-OffersX509RPK-SendsRequestedX509-TLS13": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", + "ClientCertificateType-Client-Explicit-*-SendsRequested*-TLS13*": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", + "ClientCertificateType-Client-Explicit-OffersRPK-NotActuallyConfigured-ServerRequestsRPK-TLS13*": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", + "TLS13-EmptyRecords-DTLS": "No DTLS 1.3", + "Client-Sign-RSA_PKCS1_SHA256_LEGACY-TLS12": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", + "Client-SignDefault-RSA_PKCS1_SHA256_LEGACY-TLS12": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", + "Client-Sign-RSA_PKCS1_SHA256-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", + "Client-SignDefault-RSA_PKCS1_SHA256-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", + "Client-Sign-RSA_PKCS1_SHA384-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", + "Client-SignDefault-RSA_PKCS1_SHA384-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", + "Client-Sign-RSA_PKCS1_SHA512-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", + "Client-SignDefault-RSA_PKCS1_SHA512-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", + "SendInvalidRecordType-DTLS": "Botan silently discards DTLS records of an unknown type (RFC 6347 4.1.2.7)", + "TLS13-RecordPadding-DTLS": "No DTLS 1.3", + "ClientCertificateType-Server-*-TLS12": "Botan does not support RPK certificate type negotiation in TLS 1.2", + "ClientCertificateType-Client-*-TLS12*": "Botan does not support RPK certificate type negotiation in TLS 1.2", + "ServerCertificateType-Server-*-TLS12*": "Botan does not support RPK certificate type negotiation in TLS 1.2", + "ServerCertificateType-Client-RequestsRPKOnly-*-TLS12": "Botan does not support RPK certificate type negotiation in TLS 1.2", + "ServerCertificateType-Client-RequestsRPKX509-*-TLS12": "Botan does not support RPK certificate type negotiation in TLS 1.2", + "ServerCertificateType-Client-RequestsX509RPK-*-TLS12": "Botan does not support RPK certificate type negotiation in TLS 1.2", + "ServerCertificateType-Client-RPKVerifyFail-TLS12": "Botan does not support RPK certificate type negotiation in TLS 1.2", + "ClientCertificateType-Server-RejectsInvalidDefaultOnly-VerifyPeer-TLS13": "Botan does not reject X509-only cert type extension", + "ClientCertificateType-Server-NoClientHelloCertTypes-NoSharedType-VerifyPeer-TLS13": "Botan does not reject when no shared cert type exists", + "ServerCertificateType-Server-RejectsDefaultOnly-TLS12": "Botan does not reject X509-only cert type extension as server", + "ServerCertificateType-Server-RejectsDefaultOnly-TLS13": "Botan does not reject X509-only cert type extension as server", + "ServerCertificateType-Client-RequestsRPKOnly-ServerPickedX509ByDefaultInError-TLS13": "Botan does not enforce client-side cert type rejection of unsolicited X509", + "ExtensionTrailingData-TrustAnchors-ClientHello-Server-TLS-TLS13": "No TrustAnchors extension support", + "PSK-Server-DoNotRequestClientCertificate-TLS": "Botan declines external PSKs when client certificates are required", + "PSK-Client-PSKRequired-TLS": "Botan client does not enforce PSK-only mode", + "PSK-Client-PSKRequired-TLS12-TLS": "Botan client does not enforce PSK-only mode", + "PSK-*-DTLS": "No DTLS 1.3", + "DTLS-Replay-NonMonotonic*": "Needs investigation, started failing after https://github.com/google/boringssl/commit/f94f3ed3965ea033001fb9ae006084eee408b861", + "AlternateEmptyRecordsAndWarningAlerts": "Botan has a single limit on consecutive empty records and warning alerts combined", + "CredentialSessionIDContext-*": "Botan has no session ID context to restrict which sessions may be resumed", + "ServerPadding-*": "No support for the experimental server padding extension", + "ServerPaddingServer-16kPadding": "No support for the experimental server padding extension", + "ServerPaddingServer-BasicPadding": "No support for the experimental server padding extension", + "ServerPaddingServer-OverMax": "No support for the experimental server padding extension", + "ServerPaddingServer-ResumeSession": "No support for the experimental server padding extension", + "ServerPaddingServer-TLS12": "No support for the experimental server padding extension", + "ServerPaddingServer-ZeroPadding": "No support for the experimental server padding extension", + "TLS13-Server-EqualPreference-*": "Botan has no equal-preference groups of cipher suites", + "TLS13-Server-MultiGroup-*": "Botan has no equal-preference groups of cipher suites", + "CurveTest-Server-EqualPreference-TLS13": "Botan has no equal-preference groups of key exchange groups", + "KeyShareWithServerHint-*": "Botan has no server supported groups hint; key shares are chosen directly by Policy::key_exchange_groups_to_offer", + "ServerNameExtensionServer-NoACK-*": "A Botan server always acknowledges the server_name extension", + "TLS13-Client-ResumptionAcrossNames": "Botan does not implement the TLS Flags extension, so has no ticket flags or resumption across names", + "TLS13-Client-NoResumptionAcrossNames": "Botan does not implement the TLS Flags extension, so has no ticket flags or resumption across names", + "TLS13-Server-ResumptionAcrossNames": "Botan does not implement the TLS Flags extension, so has no ticket flags or resumption across names", + "TLS13-Client-KnownAndUnknownTicketFlags-*": "Botan does not implement the TLS Flags extension, so has no ticket flags or resumption across names", + "FailCertCallback-*-CustomAlert": "Credentials_Manager cannot choose the alert sent when certificate selection fails", + "Renegotiate-Client-NoExt-Forbidden": "Botan has no option to refuse servers which do not support secure renegotiation (RFC 5746)", + "NoLegacyServerConnect-TLS13": "Botan has no option to refuse servers which do not support secure renegotiation (RFC 5746)", + "KeyUpdate-Requested-UnfinishedWrite": "BoringSSL specific API test", + "ExportKeyingMaterial-Server-HalfRTT-*": "No TLS 1.3 Early Data, yet", + "CurveID-Resume-Client": "Botan does not record the key exchange group of a TLS 1.2 session, so cannot report it on resumption", + "CurveID-Resume-Server": "Botan does not record the key exchange group of a TLS 1.2 session, so cannot report it on resumption", + "ClientCertificateTypes": "Botan ignores CertificateRequest certificate types it does not support, so cannot report them all", + "SkipCertificateStatus*": "Checks BoringSSL's message callback trace, which Botan has no equivalent of", + "TLS13-CipherPreference-*": "Botan's cipher suite preference does not depend on whether AES is hardware accelerated" + }, + "ErrorMap": { + ":CLIENTHELLO_PARSE_FAILED:": [ + ":DECODE_ERROR:" + ], + ":BAD_DECRYPT:": [ + ":DECRYPTION_FAILED_OR_BAD_RECORD_MAC:" + ], + ":ERROR_PARSING_EXTENSION:": [ + ":ERROR_PARSING_EXTENSION:", + ":DECODE_ERROR:" + ] + } +} diff --git a/src/bogo_shim/config_no_tls12.json b/src/bogo_shim/config_no_tls12.json index 271cffa1669..3a939044931 100644 --- a/src/bogo_shim/config_no_tls12.json +++ b/src/bogo_shim/config_no_tls12.json @@ -71,7 +71,29 @@ "TrailingDataWithFinished-Client-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", "TrailingDataWithFinished-Resume-Client-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", "TrailingDataWithFinished-Server-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", - "TrailingDataWithFinished-Resume-Server-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)" + "TrailingDataWithFinished-Resume-Server-TLS13": "Too picky error mapping (we detect an unexpected message during parsing)", + "UnencryptedEncryptedExtensions-DTLS": "Botan ignores all unencrypted handshake messages after key material was established, BoGo expects unexpected_message", + "PSK-Server-OmitAllPSKsOnSecondClientHello-DTLS": "Botan allows the second ClientHello to drop all PSKs (RFC 8446 4.1.2), BoGo expects missing_extension", + "PSK-Server-HRR-PSKMissing-DTLS": "Botan sends handshake_failure alert, BoGo expects illegal_parameter", + "PSK-Server-MissingPSKMode-NoMatch-DTLS": "Botan reports PSK_IDENTITY_NOT_FOUND, BoGo expects NO_SUPPORTED_PSK_MODE", + "ExtensionTrailingData-ServerName-Client-DTLS-TLS13": "Botan sends illegal_parameter for malformed server SNI; BoGo expects decode_error", + "DTLS13-HelloVerifyRequest-DTLS-Sync": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Sync": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Sync-ImplicitHandshake": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequest-DTLS-Sync-ImplicitHandshake": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequest-DTLS-Sync-SplitHandshakeRecords": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Sync-SplitHandshakeRecords": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequest-DTLS-Sync-PackHandshake": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Sync-PackHandshake": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Async": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequest-DTLS-Async": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequest-DTLS-Async-ImplicitHandshake": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Async-ImplicitHandshake": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequest-DTLS-Async-SplitHandshakeRecords": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Async-SplitHandshakeRecords": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequestEmptyCookie-DTLS-Async-PackHandshake": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-HelloVerifyRequest-DTLS-Async-PackHandshake": "Botan rejects the HelloVerifyRequest with UNSUPPORTED_PROTOCOL since there is no DTLS 1.2 to downgrade to", + "DTLS13-RejectLegacyCookie": "Botan follows RFC 9147 5.3 and aborts with an illegal_parameter alert, BoGo expects decode_error" }, "DisabledTests": { "*TLS1": "No TLS 1.0", @@ -89,12 +111,6 @@ "EMS-Forbidden-TLS13": "If we don't implement TLS 1.2, we won't offer Extended Master Secret", "RenegotiationInfo-Forbidden-TLS13": "If we don't implement TLS 1.2, we won't offer Renegotiation Info", "PointFormat-EncryptedExtensions-TLS13": "If we don't implement TLS 1.2, we won't offer Point Format in Encrypted Extensions", - "*DTLS13*": "No DTLS 1.3", - "DTLS-TLS13*": "No DTLS 1.3", - "*TLS13-DTLS": "No DTLS 1.3", - "*DTLS-TLS13": "No DTLS 1.3", - "TLS13*-DTLS-*": "No DTLS 1.3", - "MinimumVersion-*-TLS13-*DTLS": "No DTLS 1.3", "*RSA_PKCS1_MD5_SHA1": "We do not implement MD5/SHA1 concatenation anyway", "*RSA_PKCS1_SHA1*": "We do not implement PKCS1 SHA-1", "*-ECDSA_SHA1-*": "We do not implement ECDSA SHA-1", @@ -213,16 +229,6 @@ "PSK-Server-HRR-PSKMissing-TLS": "Botan sends handshake_failure alert instead of illegal_parameter", "PSK-Server-MissingPSKMode-NoMatch-TLS": "Botan reports PSK_IDENTITY_NOT_FOUND instead of NO_SUPPORTED_PSK_MODE", "DTLS-ECH*": "No ECH support", - "KeyUpdate-*-DTLS": "No DTLS 1.3", - "AppDataBeforeTLS13KeyChange-DTLS*": "No DTLS 1.3", - "UnencryptedEncryptedExtensions-DTLS": "No DTLS 1.3", - "TLS13-OnlyPadding-DTLS": "No DTLS 1.3", - "Resume-*-TLS13-TLS12-DTLS": "No DTLS 1.3", - "Downgrade-TLS12-*-DTLS": "No DTLS 1.3", - "WrongMessageType-TLS13-*-DTLS": "No DTLS 1.3", - "TrailingMessageData-TLS13-EncryptedExtensions-DTLS": "No DTLS 1.3", - "TrailingMessageData-TLS13-ServerCertificateVerify-DTLS": "No DTLS 1.3", - "KeyChangeWithBufferedMessages-DTLS": "No DTLS 1.3", "Renegotiate-DTLS-Server-Forbidden": "Botan tolerates DTLS renegotiation", "Renegotiate-DTLS-Client-Forbidden": "Botan tolerates DTLS renegotiation", "DTLS12-SendExtraFinished-*": "Botan tolerates extra Finished messages in DTLS", @@ -254,7 +260,6 @@ "ClientCertificateType-Client-OffersRPKOnly-ServerOmitsExtension-TLS13": "Botan does not reject when server omits cert_type extension and client only offers RPK", "*ML-DSA*": "Need support for the LAMPS tagged seed keys", "*MLDSA*": "No ML-DSA support in TLS, and Botan's TLS 1.2 messages do not filter out configured but unavailable signature schemes", - "TLS13-EmptyRecords-DTLS": "No DTLS 1.3", "PSK-Server-DoNotRequestClientCertificate-TLS": "Botan declines external PSKs when client certificates are required", "ClientCertificateType-Client-OffersRPKOnly-SendsRequestedRPK-TLS13": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", "ClientCertificateType-Client-OffersRPKX509-SendsRequestedRPK-TLS13": "The runner sends client_certificate_type without a CertificateRequest when resuming, which RFC 7250 forbids", @@ -270,7 +275,6 @@ "Client-SignDefault-RSA_PKCS1_SHA384-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", "Client-Sign-RSA_PKCS1_SHA512-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", "Client-SignDefault-RSA_PKCS1_SHA512-TLS13": "Botan sends an empty Certificate if no requested signature scheme suits its credentials (RFC 5246 7.4.6, RFC 8446 4.4.2)", - "TLS13-RecordPadding-DTLS": "No DTLS 1.3", "ClientCertificateType-Server-*-TLS12": "Botan does not support RPK certificate type negotiation in TLS 1.2", "ClientCertificateType-Client-*-TLS12*": "Botan does not support RPK certificate type negotiation in TLS 1.2", "ServerCertificateType-Server-*-TLS12*": "Botan does not support RPK certificate type negotiation in TLS 1.2", @@ -283,9 +287,8 @@ "ServerCertificateType-Server-RejectsDefaultOnly-TLS12": "Botan does not reject X509-only cert type extension as server", "ServerCertificateType-Server-RejectsDefaultOnly-TLS13": "Botan does not reject X509-only cert type extension as server", "ServerCertificateType-Client-RequestsRPKOnly-ServerPickedX509ByDefaultInError-TLS13": "Botan does not enforce client-side cert type rejection of unsolicited X509", - "PSK-Client-PSKRequired-TLS": "Botan client does not enforce PSK-only mode", - "PSK-Client-PSKRequired-TLS12-TLS": "Botan client does not enforce PSK-only mode", - "PSK-*-DTLS": "No DTLS 1.3", + "PSK-Client-PSKRequired-*TLS": "Botan client does not enforce PSK-only mode", + "PSK-Client-PSKRequired-TLS12-*TLS": "Botan client does not enforce PSK-only mode", "DTLS-Replay-NonMonotonic*": "Needs investigation, started failing after https://github.com/google/boringssl/commit/f94f3ed3965ea033001fb9ae006084eee408b861", "AlternateEmptyRecordsAndWarningAlerts": "Botan has a single limit on consecutive empty records and warning alerts combined", "CredentialSessionIDContext-*": "Botan has no session ID context to restrict which sessions may be resumed", @@ -314,7 +317,22 @@ "CurveID-Resume-Server": "Botan does not record the key exchange group of a TLS 1.2 session, so cannot report it on resumption", "ClientCertificateTypes": "Botan ignores CertificateRequest certificate types it does not support, so cannot report them all", "SkipCertificateStatus*": "Checks BoringSSL's message callback trace, which Botan has no equivalent of", - "TLS13-CipherPreference-*": "Botan's cipher suite preference does not depend on whether AES is hardware accelerated" + "TLS13-CipherPreference-*": "Botan's cipher suite preference does not depend on whether AES is hardware accelerated", + "KeyUpdate-DeferredSend-DTLS": "Botan does not defer KeyUpdates on the client side until the entire handshake is fully ACKed", + "KeyUpdate-MaxWriteMessage-DTLS": "Test is very slow (because it runs through 2^16 key updates)", + "KeyUpdate-MaxWriteEpoch-DTLS": "Test is very slow (because it runs through 2^16 key updates)", + "KeyUpdate-WriteMessageOverflow-DTLS": "Test is very slow (because it runs through 2^16 key updates)", + "KeyUpdate-WriteEpochOverflow-DTLS": "Test is very slow (because it runs through 2^16 key updates)", + "DTLS-Retransmit-BothTimers-TLS13*": "Botan's DTLS does not ACK previously seen messages (the 'BothTimers' test exercises some BoringSSL-internal implementation detail)", + "DTLS-Retransmit-Server-ACKForwards-TLS13*": "Retransmissions in Botan don't re-pack the datagram after ACKs", + "DTLS-Retransmit-Server-ACKIterate-TLS13*": "No API to change the MTU on an existing channel", + "DTLS-Retransmit-*SetTimeout*": "No API to change the retransmit timer mid-handshake", + "DTLS-Retransmit-ChangeMTU*": "No API to change the MTU on an existing channel", + "DTLS-Retransmit-Client-TLS13*": "Without DTLS 1.2 the client knows the version from the start, hence it processes the ACK of its first ClientHello, which BoGo expects to be ignored", + "DTLS-Retransmit-PartialProgress-Client-TLS13*": "Without DTLS 1.2 the client knows the version from the start, hence it ACKs/does not retransmit its ClientHello as BoGo expects", + "SendInvalidRecordType-DTLS": "Botan silently discards DTLS records of an unknown type (RFC 6347 4.1.2.7)", + "PSK-Server-DoNotRequestClientCertificate-DTLS": "Botan declines external PSKs when client certificates are required", + "ExtensionTrailingData-TrustAnchors-ClientHello-Server-DTLS-TLS13": "No TrustAnchors extension support" }, "ErrorMap": { ":CLIENTHELLO_PARSE_FAILED:": [ diff --git a/src/configs/repo_config.env b/src/configs/repo_config.env index e23dec81b63..afe23689b3b 100644 --- a/src/configs/repo_config.env +++ b/src/configs/repo_config.env @@ -19,10 +19,10 @@ BORINGSSL_REPO="randombit/boringssl" BORINGSSL_BRANCH="botan-bogo-20261128" # The plzn TLS conformance test harness, run against src/plzn_shim -PLZN_REPO="randombit/plzn" +PLZN_REPO="reneme/plzn" # The git revision of plzn to use -PLZN_GIT_REV=6676a26b08458f8fe5dad96316cb4624c7d3ef34 +PLZN_GIT_REV=814920de917acca6bbc48073ffa8e851180d0ee0 # The Android NDK to for the cross platform builds to Android ANDROID_NDK="android-ndk-r29" diff --git a/src/editors/vscode/scripts/bogo.py b/src/editors/vscode/scripts/bogo.py index 9601c393844..07c4cbaa78d 100755 --- a/src/editors/vscode/scripts/bogo.py +++ b/src/editors/vscode/scripts/bogo.py @@ -25,6 +25,7 @@ def find_repo_root(): BOGO_PATH = os.path.join(BORING_PATH, "ssl", "test", "runner") SHIM_PATH = os.path.join(REPO_ROOT, "botan_bogo_shim") +SHIM_CONFIG_NO_DTLS13 = os.path.join(REPO_ROOT, "src", "bogo_shim", "config_no_dtls13.json") SHIM_CONFIG_NO_TLS13 = os.path.join(REPO_ROOT, "src", "bogo_shim", "config_no_tls13.json") SHIM_CONFIG_NO_TLS12 = os.path.join(REPO_ROOT, "src", "bogo_shim", "config_no_tls12.json") SHIM_CONFIG = os.path.join(REPO_ROOT, "src", "bogo_shim", "config.json") @@ -32,6 +33,8 @@ def find_repo_root(): def main(): parser = argparse.ArgumentParser(description='Run BoringSSL Bogo tests with Botan shim') + parser.add_argument('--without-dtls-13', action='store_true', + help='Use shim config that disables DTLS 1.3') parser.add_argument('--without-tls-12', action='store_true', help='Use shim config that disables TLS 1.2') parser.add_argument('--without-tls-13', action='store_true', @@ -44,7 +47,9 @@ def main(): repo_config = RepoConfig() # Select config depending on the option - if args.without_tls_13: + if args.without_dtls_13: + config_path = SHIM_CONFIG_NO_DTLS13 + elif args.without_tls_13: config_path = SHIM_CONFIG_NO_TLS13 elif args.without_tls_12: config_path = SHIM_CONFIG_NO_TLS12 @@ -61,7 +66,7 @@ def main(): bogo_args = ';'.join(args.bogo_args) if args.bogo_args else '' extra_args = "-wait-for-debugger " if args.wait_for_debugger else "" - extra_args += "-skip-tls12 -skip-dtls " if args.without_tls_12 else "" + extra_args += "-skip-tls12 " if args.without_tls_12 else "" extra_args += "-skip-tls13 " if args.without_tls_13 else "" extra_args += "-debug -test '%s'" % bogo_args if bogo_args else '' diff --git a/src/lib/tls/dtls13/info.txt b/src/lib/tls/dtls13/info.txt new file mode 100644 index 00000000000..b6ff2820e97 --- /dev/null +++ b/src/lib/tls/dtls13/info.txt @@ -0,0 +1,14 @@ + +DTLS_13 -> 20260624 + + + +name -> "DTLS 1.3" +brief -> "Datagram Transport Layer Security 1.3" +lifecycle -> "Experimental" + + + +tls13 +bitvector + diff --git a/src/lib/tls/dtls13/tls_ack_record_dtls13.cpp b/src/lib/tls/dtls13/tls_ack_record_dtls13.cpp new file mode 100644 index 00000000000..82cac3f8ca1 --- /dev/null +++ b/src/lib/tls/dtls13/tls_ack_record_dtls13.cpp @@ -0,0 +1,113 @@ +/* +* DTLS 1.3 Acknowledgement message +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include + +#include +#include +#include +#include +#include +#include + +namespace Botan::TLS { + +namespace { + +constexpr size_t length_field_size = sizeof(uint16_t); +constexpr size_t record_number_size = sizeof(uint64_t) * 2; // epoch + sequence number + +} // namespace + +ACKs::ACKs(std::vector record_numbers) : m_record_numbers(std::move(record_numbers)) { + // RFC 9147 Section 7 + // record_numbers: A list of the records containing handshake + // messages in the current flight which the endpoint has received + // and either processed or buffered, in numerically increasing order. + std::sort(m_record_numbers.begin(), m_record_numbers.end()); +} + +ACKs::ACKs(std::span ack_record) { + BufferSlicer bs(ack_record); + + if(bs.remaining() < length_field_size) { + throw TLS_Exception(AlertType::DecodeError, "ACK record too short to contain length field"); + } + + const auto length = load_be(bs.take()); + if(bs.remaining() != length) { + throw TLS_Exception(AlertType::DecodeError, "ACK record length field does not match actual length"); + } + + if(bs.remaining() % record_number_size != 0) { + throw TLS_Exception(AlertType::DecodeError, "ACK record length not a multiple of 16 bytes"); + } + + m_record_numbers.reserve(bs.remaining() / record_number_size); + while(!bs.empty()) { + m_record_numbers.push_back(RecordNumber{ + .epoch = EpochNumber::create(load_be(bs.take())), + .sequence_number = load_be(bs.take()), + }); + } + BOTAN_ASSERT_NOMSG(m_record_numbers.size() == length / record_number_size); +} + +std::vector ACKs::serialize(size_t max_plaintext_length) const { + std::vector result; + + BOTAN_ARG_CHECK(max_plaintext_length >= length_field_size + record_number_size, + "max_plaintext_length has to allow accommodating at least one ACKed record"); + + const auto max_ack_records = (max_plaintext_length - length_field_size) / record_number_size; + BOTAN_DEBUG_ASSERT(max_ack_records > 0); + + const auto acks_to_serialize = std::min(m_record_numbers.size(), max_ack_records); + + const auto ack_bytes = acks_to_serialize * record_number_size; + const auto total_bytes = length_field_size + ack_bytes; + result.reserve(total_bytes); + + const auto length = store_be(checked_cast_to(ack_bytes)); + result.insert(result.end(), length.begin(), length.end()); + for(const auto& record_number : std::span{m_record_numbers}.last(acks_to_serialize)) { + auto one_ack = concat(store_be(record_number.epoch.index()), // + store_be(record_number.sequence_number)); + result.insert(result.end(), one_ack.begin(), one_ack.end()); + } + + BOTAN_ASSERT_NOMSG(result.size() <= max_plaintext_length); + return result; +} + +bool ACKs::validate(EpochNumber recv_epoch_of_ack_record) const { + // RFC 9147 Section 7 + // During the handshake, ACK records MUST be sent with an epoch which is + // equal to or higher than the record which is being acknowledged. + // + // RFC 9147 Section 7.2 Errata 8108 + // If any element of record_numbers in the ACK references an epoch that is + // higher than the epoch in which the ACK was received, the implementation + // MUST terminate the connection with an "illegal_parameter" alert. + // + // Note that this rule is scoped to the handshake. Post-handshake, the + // receiver of a KeyUpdate does not advance its write epoch, so it + // legitimately acknowledges records from epoch N with an ACK sent at an + // epoch < N. + if(!recv_epoch_of_ack_record.is_application_traffic()) { + for(const auto& ack : m_record_numbers) { + if(ack.epoch > recv_epoch_of_ack_record) { + return false; + } + } + } + + return true; +} + +} // namespace Botan::TLS diff --git a/src/lib/tls/dtls13/tls_ack_record_dtls13.h b/src/lib/tls/dtls13/tls_ack_record_dtls13.h new file mode 100644 index 00000000000..fd4e2892694 --- /dev/null +++ b/src/lib/tls/dtls13/tls_ack_record_dtls13.h @@ -0,0 +1,35 @@ +/* +* DTLS 1.3 Acknowledgement message +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_TLS_DTLS_ACK_H_ +#define BOTAN_TLS_DTLS_ACK_H_ + +#include + +namespace Botan::TLS { + +class BOTAN_TEST_API ACKs { + public: + explicit ACKs(std::vector record_numbers); + explicit ACKs(std::span ack_record); + + std::vector serialize(size_t max_plaintext_length) const; + + std::span record_numbers() const { return m_record_numbers; } + + /// @returns true if all ACKed record numbers are sound given the + /// epoch this ACK was originally received in + bool validate(EpochNumber recv_epoch_of_ack_record) const; + + private: + std::vector m_record_numbers; +}; + +} // namespace Botan::TLS + +#endif diff --git a/src/lib/tls/dtls13/tls_channel_io_dtls13.cpp b/src/lib/tls/dtls13/tls_channel_io_dtls13.cpp new file mode 100644 index 00000000000..1dcb2dd28c8 --- /dev/null +++ b/src/lib/tls/dtls13/tls_channel_io_dtls13.cpp @@ -0,0 +1,655 @@ +/* +* DTLS 1.3 Channel I/O +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include + +#include +#include +#include + +#include + +namespace Botan::TLS { + +DTLS_Channel_IO::DTLS_Channel_IO(Connection_Side side, + std::shared_ptr policy_ptr, + std::shared_ptr callbacks) : + Channel_IO(side, TLS_Flavor::DTLS, std::move(policy_ptr), std::move(callbacks)), + m_record_layer(policy()), + m_handshake_layer(side), + m_retransmission_timer(policy(), shared_callbacks()), + // RFC 9147 5.8.1: "DTLS servers start in the WAITING state, but with + // empty buffers and no retransmit timer." I.e. the server awaits the + // client's first flight while the client does not await anything. + m_expected_from_peer(side == Connection_Side::Server ? Expected_Response::Flight : Expected_Response::None) { + // In DTLS we flush out the payload one datagram at a time. Hence, the output + // buffer is capped to the application-defined MTU or the maximum record + // length if the application provides a larger MTU. + m_outgoing_datagram.reserve(std::min(policy().dtls_default_mtu(), to_underlying(MAX_CIPHERTEXT_SIZE_TLS13))); +} + +void DTLS_Channel_IO::send_data(Record_Type record_type, std::span payload, Cipher_State* cipher_state) { + BOTAN_STATE_CHECK(m_outgoing_datagram.empty()); + + std::ignore = m_record_layer.prepare_record(record_type, payload, policy(), cipher_state, m_outgoing_datagram); + callbacks().tls_emit_data(m_outgoing_datagram); + m_outgoing_datagram.clear(); +} + +void DTLS_Channel_IO::send_flight(std::vector flight, Expected_Response expected) { + // We must not start a new interaction while we are still waiting for the + // peer's response flight to a previous one (RFC 9147 5.8.4 allows + // concurrency for some message categories, but we do not implement it). + BOTAN_STATE_CHECK(m_expected_from_peer == Expected_Response::None); + BOTAN_STATE_CHECK(m_outgoing_datagram.empty()); + + // RFC 9147 Section 4.3 + // DTLS messages MAY be fragmented into multiple DTLS records. Each DTLS + // record MUST fit within a single datagram. [...] Multiple DTLS records + // MAY be placed in a single datagram. Records are encoded consecutively. + // [...] Records MUST NOT span datagrams. + // + // We make use of this and pack handshake message fragments into handshake + // records (even across message boundaries, as long as they share an epoch) + // and handshake records into datagrams, as tightly as the MTU configured in + // the policy allows. + + // A fragment must contain at least one payload byte in addition to its + // handshake header to make progress. + constexpr size_t min_fragment_size = DTLS_Handshake_Layer::FRAGMENT_HEADER_LENGTH + 1; + + PackedHandshakeMessageFragments current_record_payload; // record currently being packed with fragments + std::optional current_record_epoch; + + // Seals the pending record and appends it to the pending datagram. The + // record layer tracks the sealed record for potential retransmission. + const auto flush_record = [&]() { + if(current_record_payload.empty()) { + return; + } + + record_layer().prepare_handshake_record(std::exchange(current_record_payload, {}), + m_outgoing_datagram, + policy(), + cipher_state().get(), + current_record_epoch); + }; + + // Seals the pending record and emits the pending datagram. + const auto flush_datagram = [&]() { + flush_record(); + if(!m_outgoing_datagram.empty()) { + callbacks().tls_emit_data(m_outgoing_datagram); + m_outgoing_datagram.clear(); + } + }; + + for(const auto& msg : flight) { + BOTAN_ARG_CHECK(std::holds_alternative(msg), + "DTLS 1.3 can only send proper handshake messages in its flights"); + + const auto& msg_info = std::get(msg); + // RFC 9147 5 + // DTLS implementations do not use the TLS 1.3 "compatibility mode" [...]. + // + // `msg` is either Flight::Message_Info or Flight::Dummy_ChangeCipherSpec. + + // A record must not contain fragments of different protection epochs. + // Note that the sealed record may still share the pending datagram with + // records of other epochs (e.g. an unprotected ServerHello may be packed + // with a protected EncryptedExtensions record in the same datagram). + if(current_record_epoch != msg_info.epoch) { + flush_record(); + } + current_record_epoch = msg_info.epoch; + + // The payload limit of a record that occupies a datagram all by itself, + // given the record overhead of the current epoch. + const size_t record_payload_limit = + record_layer().record_payload_size_limit(policy(), cipher_state().get(), msg_info.epoch); + + // Space left for another fragment in the pending record, taking the + // records already packed into the pending datagram into account. If not + // even a minimal fragment fits, the pending record (and with it the + // pending datagram) is full. + const size_t packed_bytes = m_outgoing_datagram.size() + current_record_payload.size(); + if(packed_bytes + min_fragment_size > record_payload_limit) { + flush_datagram(); + } + + // The first fragment of this message may fill up the space that is left + // in the pending record; all further fragments may fill up entire + // records. + const auto first_fragment_size = + static_cast(record_payload_limit - m_outgoing_datagram.size() - current_record_payload.size()); + + // TODO: This could be optimized with an out-param to avoid allocation + // and copy for each fragment. I.e. just hand it a reference to + // `current_record_payload` and let it append the fragment directly. + const auto fragments = handshake_layer().fragment_message( + msg_info.wire_type, msg_info.serialized, static_cast(record_payload_limit), first_fragment_size); + + for(const auto& fragment : fragments) { + if(m_outgoing_datagram.size() + current_record_payload.size() + fragment.size() > record_payload_limit) { + // The pending record (and with it the pending datagram) is full. + flush_datagram(); + } + current_record_payload.get().insert(current_record_payload.get().end(), fragment.begin(), fragment.end()); + } + } + + flush_datagram(); + + if(expected == Expected_Response::Flight) { + // The peer is expected to respond with a flight of its own. Until that + // flight completes, an ACK for this flight cannot end the interaction. + m_expected_from_peer = Expected_Response::Flight; + } + + // TODO: Consider omitting the retransmission timer for the HelloRetryRequest + // flight, as suggested by RFC 9147 Section 3.1 + // + // RFC 9147 3.1 + // The server also maintains a retransmission timer for messages it sends + // (other than HelloRetryRequest) [...]. Not applying retransmissions to + // the HelloRetryRequest avoids the need to create state on the server. + arm_retransmission_and_flight_timers(); +} + +void DTLS_Channel_IO::handle_key_update(const Key_Update& key_update) { + // RFC 9147 8. + // With a 128-bit key as in AES-128, rekeying 2^64 times has a high + // probability of key reuse within a given connection. [...] In order to + // provide an extra margin of security, sending implementations MUST NOT + // allow the epoch to exceed 2^48-1. [...] + // + // RFC 9147 8. (Errata-ID 8050) + // After the handshake, each epoch change consumes a message_seq value, + // which is limited to 2^16-1. Both sending and receiving implementations + // MAY instead enforce an epoch limit of 2^16-1. In this case, the + // implementation MUST check for this limit, if reached, terminate the + // association. + // + // If the just-received KeyUpdate would move the epoch number beyond the + // limit of 2^16-1, we reject it as unexpected message. + if(cipher_state()->current_read_epoch_number().is_exhausted_for_dtls()) { + throw TLS_Exception(Alert::UnexpectedMessage, "Cannot update keys: maximum DTLS epoch number reached"); + } + + Channel_IO::handle_key_update(key_update); +} + +bool DTLS_Channel_IO::can_send_post_handshake_messages() const { + // RFC 9147 5.8.4 + // Sending multiple instances of messages of a given category without + // having completed earlier transmissions is allowed for some categories, + // but not for others. Specifically, a server MAY send multiple + // NewSessionTicket messages at once without awaiting ACKs for earlier + // NewSessionTicket messages first. [...] In contrast, implementations + // MUST NOT send KeyUpdate, NewConnectionId, or RequestConnectionId + // messages if an earlier message of the same type has not yet been + // acknowledged. + // + // RFC 9147 8. Key Updates + // In order to facilitate epoch reconstruction, implementations MUST NOT + // send records with the new keys or send a new KeyUpdate until the + // previous KeyUpdate has been acknowledged [...]. + // + // Right now, the only post-handshake messages we support are KeyUpdate and + // NewSessionTicket. For simplicity, we block all post-handshake messages + // while a KeyUpdate is unacknowledged so that no further post-handshake + // messages are sent in the already-doomed epoch. That makes us compatible + // with BoringSSL, which enforces this restriction even though the RFC does + // not require it explicitly (see BoGo test "KeyUpdate-ExtraMessage-DTLS"). + return Channel_IO::can_send_post_handshake_messages() && !has_unacknowledged_key_update(); +} + +void DTLS_Channel_IO::send_key_update(const Key_Update& msg) { + BOTAN_STATE_CHECK(!has_unacknowledged_key_update()); + // A KeyUpdate must not be sent while an interaction is still open that + // awaits a response flight from the peer (i.e. outside the handshake). + BOTAN_STATE_CHECK(m_expected_from_peer == Expected_Response::None); + BOTAN_STATE_CHECK(m_outgoing_datagram.empty()); + + const auto serialized_key_update = Handshake_Layer::serialize(msg); + auto msg_bytes = handshake_layer().fragment_message( + Handshake_Type::KeyUpdate, + serialized_key_update, + checked_cast_to(DTLS_Handshake_Layer::FRAGMENT_HEADER_LENGTH + serialized_key_update.size())); + + BOTAN_ASSERT_NOMSG(msg_bytes.size() == 1); // KeyUpdate is small enough to always fit into a single fragment + const auto record_number = + record_layer().prepare_handshake_record(PackedHandshakeMessageFragments(std::move(msg_bytes.front())), + m_outgoing_datagram, + policy(), + cipher_state().get()); + + callbacks().tls_emit_data(m_outgoing_datagram); + m_outgoing_datagram.clear(); + + // RFC 9147 8. + // [...] KeyUpdates MUST be acknowledged. In order to facilitate epoch + // reconstruction [...], implementations MUST NOT send records with the + // new keys or send a new KeyUpdate until the previous KeyUpdate has + // been acknowledged [...]. + // + // The actual call to cipher_state->update_write_keys() is + // deferred to the handling of the respective acknowledgement. + m_pending_key_update_record = record_number; + + arm_retransmission_and_flight_timers(); +} + +void DTLS_Channel_IO::send_acknowledgements() { + // There might be nothing to acknowledge, e.g. when all recently received + // handshake records contained fragments that had to be discarded. Don't + // emit a pointless empty ACK record in that case. + if(!record_layer().has_outstanding_acknowledgements()) { + return; + } + + const auto max_plaintext_length = record_layer().record_payload_size_limit(policy(), cipher_state().get()); + send_data(Record_Type::ACK, m_record_layer.acknowledgements().serialize(max_plaintext_length), cipher_state().get()); +} + +void DTLS_Channel_IO::notify_protocol_version_committed() { + Channel_IO::notify_protocol_version_committed(); + m_dtls_version_committed = true; +} + +void DTLS_Channel_IO::notify_protocol_version_committed_and_flight_superseded() { + notify_protocol_version_committed(); + maybe_clear_retransmission_buffer(); +} + +void DTLS_Channel_IO::notify_received_complete_flight(Expected_Response expected_by_peer) { + // We are notified only about the completion of a flight that we were + // waiting for. Anything else would indicate a bug in the handshake state + // machine. + BOTAN_STATE_CHECK(m_expected_from_peer == Expected_Response::Flight); + m_expected_from_peer = Expected_Response::None; + + if(expected_by_peer == Expected_Response::Flight) { + // We have everything we needed, no reason to do any ACKing anymore: our + // response flight will implicitly acknowledge the peer's flight. + record_layer().clear_outstanding_acknowledgements(); + } else { + // RFC 9147 5.7 + // When a handshake flight is sent without any expected response, as + // is the case with the client's final flight [...], the flight must + // be acknowledged with an ACK message. + // + // The final flight must always be acknowledged. We do that instantly. + send_acknowledgements(); + } + + // The interaction's open flight was received. Whatever follows — our + // response flight, or closing the connection — re-arms or disarms the + // timers as appropriate. + m_retransmission_timer.cancel(); + m_ack_timer.cancel(); +} + +void DTLS_Channel_IO::notify_closed_for_writing() { + Channel_IO::notify_closed_for_writing(); + m_ack_timer.cancel(); + m_retransmission_timer.cancel(); + m_outgoing_datagram.clear(); + + // Even when a currently-pending KeyUpdate were to be ACKed by the peer now, + // we wouldn't be able to send anything under the new keys anymore... + m_pending_key_update_record.reset(); +} + +std::optional DTLS_Channel_IO::next_retransmission_timeout() const { + const auto next_ack = m_ack_timer.remaining(callbacks()); + const auto next_retransmission = m_retransmission_timer.next_timeout(); + + if(!next_ack && !next_retransmission) { + return std::nullopt; + } + + return std::min(next_ack.value_or(std::chrono::milliseconds::max()), + next_retransmission.value_or(std::chrono::milliseconds::max())); +} + +void DTLS_Channel_IO::maybe_clear_retransmission_buffer() { + // If we're not sure that the peer is using DTLS 1.3, we must not clear + // the resend buffer as soon as we received any fragment of the peer's + // flight. If some fragment got lost, we can't ACK and therefore are + // forced to retransmit our entire previous flight. + if(m_dtls_version_committed) { + record_layer().clear_resend_buffer(); + + // RFC 9147 7. + // [...] receiving a message from a handshake flight implicitly + // acknowledges all messages from the previous flight(s). + // + // The peer's progress implicitly acknowledged our flight, so we stop + // retransmitting. But unless the peer's flight is complete (in which + // case notify_received_complete_flight() ends the interaction), we are + // still waiting for the peer to finish what it started. The blanket + // flight timeout keeps guarding against a peer that stalls midway. + m_retransmission_timer.stop_retransmissions(); + } +} + +void DTLS_Channel_IO::retransmit() { + // Pack the retransmitted records into datagrams up to the MTU, just like + // send_flight() did for the original transmission. This keeps the packing + // of a full retransmission identical to the original flight. + const size_t mtu = policy().dtls_default_mtu(); + + std::vector datagram; + for(const auto& record_to_write : record_layer().prepare_unacknowledged_records(policy(), cipher_state().get())) { + if(!datagram.empty() && datagram.size() + record_to_write.size() > mtu) { + callbacks().tls_emit_data(datagram); + datagram.clear(); + } + datagram.insert(datagram.end(), record_to_write.begin(), record_to_write.end()); + } + if(!datagram.empty()) { + callbacks().tls_emit_data(datagram); + } +} + +void DTLS_Channel_IO::maybe_schedule_read_epoch_pruning(EpochNumber epoch_used_for_deprotection) { + using namespace std::chrono_literals; + + // Whenever we see an incoming record that was deprotected with a previously + // unseen epoch, we know that we and also the peer successfully advanced to + // that epoch. + const bool successful_epoch_advancement_detected = [&] { + if(epoch_used_for_deprotection > m_newest_active_epoch) { + m_newest_active_epoch = epoch_used_for_deprotection; + return true; + } else { + return false; + } + }(); + + // RFC 9147 8. + // Due to the possibility of an ACK message for a KeyUpdate being lost and + // thereby preventing the sender of the KeyUpdate from updating its keying + // material, receivers MUST retain the pre-update keying material until + // receipt and successful decryption of a message using the new keys. + if(!successful_epoch_advancement_detected) { + return; + } + + // RFC 9147 4.2.1 + // Implementations [...] MAY choose to retain keying material from + // previous epochs for up to the default MSL specified for TCP [RFC0793] + // to allow for packet reordering. + // + // RFC 9147 5.8.1 + // In addition, for at least twice the default MSL defined for [RFC0793], + // when in the FINISHED state, the server MUST respond to retransmission + // of the client's final flight with a retransmit of its ACK. + // + // RFC 9293 4. + // MSL: Maximum Segment Lifetime, the time a TCP segment can exist in the + // internetwork system. Arbitrarily defined to be 2 minutes. + // + // Note: if a client performs a KeyUpdate immediately after finishing the + // handshake, the associated 2 minutes pruning delay will overtake the + // 4 minutes pruning delay of the handshake epoch and remove the + // handshake epoch earlier than mandated, because we always defensively + // prune all epochs older than the just-instated one. We consider this + // acceptable as pathological. + const auto is_initial_application_traffic_epoch = epoch_used_for_deprotection.application_traffic_index() == 0; + const auto prune_delay = is_initial_application_traffic_epoch ? 4min : 2min; + SingleshotTimer::start_detached( + shared_callbacks(), prune_delay, [weak = weak_from_this(), epoch_used_for_deprotection] { + if(auto self = weak.lock()) { + if(auto cs = self->cipher_state()) { + auto* dcs = as_dtls_cipher_state(cs.get()); + BOTAN_ASSERT_NONNULL(dcs); + dcs->prune_read_epochs_older_than(epoch_used_for_deprotection); + self->m_record_layer.prune_replay_windows_older_than(epoch_used_for_deprotection); + } + } + }); +} + +void DTLS_Channel_IO::arm_retransmission_and_flight_timers() { + if(!m_retransmission_timer.retransmissions_armed()) { + m_retransmission_timer.start([weak = weak_from_this()] { + if(auto self = weak.lock()) { + self->retransmit(); + } + }); + } +} + +void DTLS_Channel_IO::init(const std::shared_ptr& channel) { + m_channel = channel; + m_retransmission_timer.set_timeout_handler([weak_channel = std::weak_ptr(channel)] { + if(auto c = weak_channel.lock()) { + c->shutdown(); + } + }); +} + +void DTLS_Channel_IO::process(const Handshake_Record& record) { + BOTAN_ASSERT_NOMSG(record.epoch.has_value()); + maybe_schedule_read_epoch_pruning(*record.epoch); + + // Handshake records need to be fed to the handshake layer before + // their messages can be consumed by the channel + const auto result = handshake_layer().copy_data(policy(), record); + + // RFC 9147 7. + // During the handshake, ACKs only cover the current outstanding flight + // (this is possible because DTLS is generally a lock-step protocol). + // In particular, receiving a message from a handshake flight implicitly + // acknowledges all messages from the previous flight(s). + // + // Handshake_Layer::copy_data() reports progress if a handshake message + // fragment with a previously unprocessed sequence number was queued for + // reassembly. This indicates progress and therefore ACKs our previously sent + // flight implicitly. Discarded fragments (retransmissions of consumed + // messages or messages beyond the buffering window) do not count as + // progress. + // + // Note: This assumes that we only send our flight once we fully received a + // flight from the peer. This is a hard requirement in TLS 1.3. + if(result == Handshake_Layer::CopyDataResult::Consumed || + result == Handshake_Layer::CopyDataResult::ConsumedPartially) { + if(!record.epoch->is_application_traffic()) { + maybe_clear_retransmission_buffer(); + } + } + + // RFC 9147 7. + // Implementations MUST NOT acknowledge records containing handshake + // messages or fragments which have not been processed or buffered. + // Otherwise, deadlock can ensue. + // + // If the handshake record was fully consumed or was a retransmission of a + // previously consumed message, we can (re-)acknowledge this record. + if(result == Handshake_Layer::CopyDataResult::Consumed || + result == Handshake_Layer::CopyDataResult::DiscardedDuplicate) { + record_layer().acknowledge_handshake_record( + { + .epoch = record.epoch.value(), + .sequence_number = record.sequence_number.value(), + }, + policy()); + + // RFC 9147 7.1 + // [...] it is RECOMMENDED that [an implementation generates] ACKs + // under two circumstances: + // + // - [...] + // - When they have received part of a flight and do not immediately + // receive the rest of the flight [...]. One approach is to set a + // timer [...] and then send an ACK when that timer expires. + // + // This opportunistically sets such a timer which is cancelled once the + // peer's flight completes: our response flight implicitly acknowledges + // it, or we acknowledge it explicitly right away. Otherwise, the timer + // will eventually emit ACKs to the peer. + if(m_dtls_version_committed && !m_ack_timer.armed()) { + const auto ack_delay = std::chrono::milliseconds(policy().dtls_acknowledgement_delay()); + m_ack_timer = SingleshotTimer::start(shared_callbacks(), ack_delay, [weak = weak_from_this()] { + if(auto self = weak.lock()) { + self->send_acknowledgements(); + } + }); + } + + // RFC 9147 5.8.1 + // [When] the implementation reads a retransmitted flight from the peer + // when none of the messages that it sent in response to that flight + // have been acknowledged: the implementation [...] retransmits the + // flight [and] adjusts and re-arms the retransmit timer. The rationale + // here is that the receipt of a duplicate message is the likely result + // of timer expiry on the peer and therefore suggests that part of one's + // previous flight was lost. + // + // We currently do not implement this retransmission trigger. Instead, re- + // transmissions are solely driven by the retransmission timer that is + // armed when we emit a flight for the first time. + // + // This trigger would be particularly useful when we want to refrain from + // retransmitting HelloRetryRequests as mandated by RFC 9147 Section 3.1. + // Then, we would retransmit the HRR only on re-receipt of the peer's + // initial ClientHello. + // + // TODO: Retransmit un-acknowledged flights on re-receipt of a flight from + // the peer, and stop arming the retransmission timer for HRR. + // + // Note: This mirrors the behavior of BoringSSL (crbug.com/383016430). + } + + // Tracking useless records protects against an authenticated misbehaving + // peer, only. + if(auto channel = m_channel.lock(); channel != nullptr && record.epoch->is_protected()) { + switch(result) { + case Handshake_Layer::CopyDataResult::Consumed: + case Handshake_Layer::CopyDataResult::ConsumedPartially: + // The record contained some new fragment that was kept. + channel->reset_useless_records(); + break; + case Handshake_Layer::CopyDataResult::Discarded: + // The record was discarded (e.g. because it contained fragments that + // are too far in the future). + channel->note_useless_record(policy()); + break; + case Handshake_Layer::CopyDataResult::DiscardedDuplicate: + // The record contained only duplicate fragments. This is "neutral" + // and does not count toward the limit of useless records. + // Otherwise, a large retransmitted flight could exhaust the limit. + break; + } + } +} + +void DTLS_Channel_IO::process(const ACK_Record& ack_record) { + BOTAN_ASSERT_NOMSG(ack_record.epoch.has_value()); + maybe_schedule_read_epoch_pruning(*ack_record.epoch); + + // If we receive ACKs before we know for sure that the peer is using + // DTLS 1.3, we ignore them. The peer might still pick DTLS 1.2, and as + // a result would depend on a full flight retransmission. + // + // This mirrors the behavior of BoringSSL and is needed to pass + // relevant BoGo tests. + if(!m_dtls_version_committed) { + return; + } + + const auto acks = ACKs(ack_record.payload); + + // RFC 9147 Section 7.2 Errata 8108 + // If any element of record_numbers in the ACK references an epoch that is + // higher than the epoch in which the ACK was received, the implementation + // MUST terminate the connection with an "illegal_parameter" alert. + // + // Note that this allows an attacker to tear-down a connection via a + // plaintext ACK. There is a discussion about this: + // github.com/tlswg/dtls13-spec/issues/331 - For now, we follow BoringSSL's + // interpretation and throw an alert even in the case of a plaintext ACK, as + // long as we have not yet seen a protected record from the peer (this check + // is done in the record layer). + // + // TODO: Revisit once the spec issue is resolved. + if(!acks.validate(*ack_record.epoch)) { + throw TLS_Exception(Alert::IllegalParameter, "ACK record refers to an invalid record number"); + } + + const auto ack_effect = record_layer().handle_acknowledgements(acks); + if(ack_effect == ACK_Effect::ACKed_Everything) { + // RFC 9147 5.8.1 + // Upon receiving an ACK for a complete flight, the implementation + // cancels all retransmissions and either remains in WAITING, or, if + // the ACK was for the final flight, transitions to FINISHED. + // + // If we are still waiting for a flight from the peer, we merely stop the + // retransmissions and keep the blanket flight timeout armed: it guards + // against a peer that acknowledged our flight but then stalls before + // completing its own. Otherwise the ACK ends the interaction and there + // is nothing left to wait for. + if(m_expected_from_peer == Expected_Response::Flight) { + m_retransmission_timer.stop_retransmissions(); + } else { + m_retransmission_timer.cancel(); + } + } + + // Tracking useless messages protects against an authenticated misbehaving + // peer, only. + if(auto channel = m_channel.lock(); channel != nullptr && ack_record.epoch->is_protected()) { + if(ack_effect == ACK_Effect::ACKed_Nothing) { + channel->note_useless_record(policy()); + } else { + channel->reset_useless_records(); + } + } + + const auto locked_cs = cipher_state(); + auto* cs = as_dtls_cipher_state(locked_cs.get()); + + if(has_unacknowledged_key_update() && + !record_layer().has_unacknowledged_record(m_pending_key_update_record.value())) { + BOTAN_ASSERT_NONNULL(cs); + cs->update_write_keys(); + m_pending_key_update_record.reset(); + } + + // If there's nothing left to retransmit, we can safely discard any + // outdated write epochs. + if(cs != nullptr && !record_layer().has_unacknowledged_records()) { + cs->prune_write_epochs_older_than(cs->current_write_epoch_number()); + } + + // RFC 9147 7.2 + // Upon receipt of an ACK that leaves it with only some messages from + // a flight having been acknowledged, an implementation SHOULD + // retransmit the unacknowledged messages or fragments. + // + // TODO: In the future we might want to use this cipher_state to trigger + // an immediate retransmission after receiving a partial ACK from + // the peer. For now, we just wait for the retransmission timer + // (`retransmit()`) to fire. + // + // Not sending retransmissions immediately mirrors the current behavior + // of BoringSSL and is expected by BoGo tests (crbug.com/383016430). +} + +void DTLS_Channel_IO::validate(const TransparentRecord& record) { + std::visit( + [this](const auto& r) { + BOTAN_ASSERT_NOMSG(r.epoch.has_value()); + maybe_schedule_read_epoch_pruning(*r.epoch); + }, + record); +} + +} // namespace Botan::TLS diff --git a/src/lib/tls/dtls13/tls_channel_io_dtls13.h b/src/lib/tls/dtls13/tls_channel_io_dtls13.h new file mode 100644 index 00000000000..0e46a71eb52 --- /dev/null +++ b/src/lib/tls/dtls13/tls_channel_io_dtls13.h @@ -0,0 +1,103 @@ +/* +* DTLS Channel IO - handle DTLS IO specifics +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_TLS_CHANNEL_IO_DTLS13_H_ +#define BOTAN_TLS_CHANNEL_IO_DTLS13_H_ + +#include +#include +#include +#include +#include +#include + +namespace Botan::TLS { + +class Channel_Impl_13; + +class DTLS_Channel_IO final : public Channel_IO, + public std::enable_shared_from_this { + public: + DTLS_Channel_IO(Connection_Side side, + std::shared_ptr policy_ptr, + std::shared_ptr callbacks); + + public: + void handle_key_update(const Key_Update& key_update) override; + bool can_send_post_handshake_messages() const override; + + void notify_protocol_version_committed() override; + void notify_protocol_version_committed_and_flight_superseded() override; + void notify_received_complete_flight(Expected_Response expected_by_peer) override; + void notify_closed_for_writing() override; + + std::optional next_retransmission_timeout() const override; + + private: + void init(const std::shared_ptr& channel) override; + + void process(const Handshake_Record& record) override; + void process(const ACK_Record& ack_record) override; + void validate(const TransparentRecord& record) override; + + void send_flight(std::vector flight, Expected_Response expected) override; + void send_data(Record_Type record_type, std::span payload, Cipher_State* cipher_state) override; + void send_acknowledgements(); + void send_key_update(const Key_Update& msg) override; + + bool has_unacknowledged_key_update() const { return m_pending_key_update_record.has_value(); } + + void maybe_schedule_read_epoch_pruning(EpochNumber epoch_used_for_deprotection); + void arm_retransmission_and_flight_timers(); + void maybe_clear_retransmission_buffer(); + void retransmit(); + + DTLS_Record_Layer& record_layer() override { return m_record_layer; } + + const DTLS_Record_Layer& record_layer() const override { return m_record_layer; } + + DTLS_Handshake_Layer& handshake_layer() override { return m_handshake_layer; } + + const DTLS_Handshake_Layer& handshake_layer() const override { return m_handshake_layer; } + + private: + DTLS_Record_Layer m_record_layer; + DTLS_Handshake_Layer m_handshake_layer; + + SingleshotTimer m_ack_timer; + RetransmissionTimer m_retransmission_timer; + + /** + * The response that the peer still owes us for the currently open + * interaction (a handshake or a post-handshake message exchange): either + * a further flight of handshake messages or nothing (in which case DTLS + * peers acknowledge the interaction's final flight explicitly, see + * RFC 9147 5.7). + * + * A server starts out expecting the client's first flight. The + * expectation is set when sending a flight that expects a response + * flight and cleared when the awaited flight completes (RFC 9147 + * 5.8.1). It decides whether + * an ACK for a complete flight ends the interaction ("final ACK") or + * merely stops the retransmissions while we keep waiting for the peer's + * progress. + */ + Expected_Response m_expected_from_peer; + + std::weak_ptr m_channel; + std::optional m_pending_key_update_record; + + bool m_dtls_version_committed = false; + EpochNumber m_newest_active_epoch = EpochNumber::unprotected(); + + secure_vector m_outgoing_datagram; +}; + +} // namespace Botan::TLS + +#endif diff --git a/src/lib/tls/dtls13/tls_cipher_state_dtls13.cpp b/src/lib/tls/dtls13/tls_cipher_state_dtls13.cpp new file mode 100644 index 00000000000..b01795a025e --- /dev/null +++ b/src/lib/tls/dtls13/tls_cipher_state_dtls13.cpp @@ -0,0 +1,349 @@ +/* +* DTLS 1.3 cipher state +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Botan::TLS { + +namespace { + +/** + * Computes the record number mask (RFC 9147 Section 4.2.3) for the + * given write epoch from a 16-byte ciphertext sample. + */ +std::array compute_record_number_mask(const DTLS_Cipher_State::Epoch& epoch, + const Ciphersuite& ciphersuite, + std::span ct) { + auto mask = typecast_copy>(ct); + + // TODO: it would be helpful to provide a canonical block/stream cipher name + // from the Ciphersuite (e.g. "AES-128" or "ChaCha20") or any other way + // to avoid string comparisons here. + + if(ciphersuite.to_string() == "CHACHA20_POLY1305_SHA256") { + auto chacha = StreamCipher::create_or_throw("ChaCha20"); + + // RFC 8439 2.3 + // chacha20_block(key, counter, nonce) + // + // RFC 9147 4.2.3 + // Mask = ChaCha20(sn_key, Ciphertext[0..3], Ciphertext[4..15]) + + const uint64_t counter = load_le(ct.first<4>()); + const auto nonce = ct.last<12>(); + + chacha->set_key(epoch.sequence_number_key); + chacha->set_iv(nonce); + chacha->seek(counter * 64); + chacha->write_keystream(mask); + } else if(ciphersuite.to_string().starts_with("AES_128")) { + auto aes = BlockCipher::create_or_throw(fmt("AES-128")); + aes->set_key(epoch.sequence_number_key); + aes->encrypt(mask); + } else if(ciphersuite.to_string().starts_with("AES_256")) { + auto aes = BlockCipher::create_or_throw(fmt("AES-256")); + aes->set_key(epoch.sequence_number_key); + aes->encrypt(mask); + } else { + throw Not_Implemented( + fmt("Ciphersuite {} is not supported for DTLS 1.3 record number masking", ciphersuite.to_string())); + } + + return mask; +} + +/** + * Computes the record number mask (RFC 9147 Section 4.2.3) and XORs + * it with the given sequence number hint to (de)protect it. + */ +SequenceNumberHint xor_record_sequence_number(const DTLS_Cipher_State::Epoch& epoch, + const Ciphersuite& ciphersuite, + std::span ciphertext, + SequenceNumberHint seqno_hint) { + BOTAN_ARG_CHECK(ciphertext.size() >= 16, "Record payload must be at least 16 bytes in DTLS 1.3"); + const auto mask = compute_record_number_mask(epoch, ciphersuite, ciphertext.first<16>()); + + return std::visit( + [&](const T seqno) -> SequenceNumberHint { + // RFC 9147 Section 4.2.3 + // The encrypted sequence number is computed by XORing the leading + // bytes of the mask with the on-the-wire representation of the + // sequence number. Decryption is accomplished by the same process. + return static_cast(seqno ^ load_be(std::span{mask}.first())); + }, + seqno_hint); +} + +// RFC 9147 5.9 +// Section 7.1 of [TLS13] specifies that HKDF-Expand-Label uses a label +// prefix of "tls13 ". For DTLS 1.3, that label SHALL be "dtls13". This +// ensures key separation between DTLS 1.3 and TLS 1.3. Note that there is +// no trailing space [...]. +constexpr Cipher_State::ExpansionLabelPrefix dtls_expansion_label_prefix{'d', 't', 'l', 's', '1', '3'}; + +} // namespace + +DTLS_Cipher_State::DTLS_Cipher_State(Connection_Side side, std::string_view prf_algo) : + Cipher_State(side, prf_algo, dtls_expansion_label_prefix) {} + +DTLS_Cipher_State::~DTLS_Cipher_State() = default; + +RecordNumber DTLS_Cipher_State::protect_record(Record_Type type, + std::span payload, + size_t padding_bytes, + secure_vector& out, + std::optional epoch_number) { + BOTAN_STATE_CHECK(!m_write_epochs.empty()); + BOTAN_ARG_CHECK(!epoch_number.has_value() || epoch_number->is_protected(), + "epoch_number must implicate record protection"); + + auto& epoch = [&]() -> Epoch& { + if(!epoch_number.has_value()) { + BOTAN_STATE_CHECK(current_write_epoch_number().is_protected()); + return m_write_epochs.back(); + } else { + const auto eitr = std::find_if(m_write_epochs.rbegin(), m_write_epochs.rend(), [&](const auto& write_epoch) { + return write_epoch.number == *epoch_number; + }); + + if(eitr == m_write_epochs.rend()) { + throw TLS_Exception(Alert::InternalError, "No write epoch found for requested epoch number"); + } + + return *eitr; + } + }(); + + // 1. Figure out how many encrypted bytes we will produce + // RFC 9147 Figure 2 DTLSInnerPlaintext = content | type | zeros + + const size_t ciphertext_size = [&] { + while(true) { + const auto ct_size = protected_record_length(epoch, payload.size(), padding_bytes); + + // RFC 9147 Section 4.2.3 + // Senders MUST pad short plaintexts out (using the conventional + // record padding mechanism) in order to make a suitable-length + // ciphertext. Note that most of the DTLS AEAD algorithms have a 16 + // byte authentication tag and need no padding. However, some + // algorithms, such as TLS_AES_128_CCM_8_SHA256, have a shorter + // authentication tag and may require padding for short inputs. + if(ct_size >= 16) { + return ct_size; + } else { + padding_bytes += 1; // Increase padding until ciphertext is at least 16 bytes + } + } + }(); + + // 2. Set up *pre-encryption* unified_hdr, which serves as + // Associated Data (AD). + + auto unified_header = UnifiedHeader_DTLS{ + .epoch_bits = static_cast(epoch.number.index() & 0b00000011), + .connection_id = std::nullopt, // TODO: support CID + .sequence_number = static_cast(epoch.sequence_number), // TODO: support 16 and 8 bit seq_no + .length = checked_cast_to(ciphertext_size), // TODO: support length field omission + }; + + // 3. Marshall and protect the record + + const auto marshalled_record = + marshall_and_protect(epoch, unified_header.serialize(), payload, type, padding_bytes, out); + + // 4. Mask seq bytes (RFC 9147 Section 4.2.3 Record Number Encryption) and + // render the header into the output buffer + + const size_t header_size = unified_header.serialized_byte_length(); + BOTAN_ASSERT_NOMSG(marshalled_record.size() >= header_size); + unified_header.sequence_number = xor_record_sequence_number( + epoch, ciphersuite(), marshalled_record.subspan(header_size), unified_header.sequence_number); + unified_header.serialize_to(marshalled_record.first(header_size)); + + return { + .epoch = epoch.number, + .sequence_number = epoch.sequence_number++, + }; +} + +std::optional DTLS_Cipher_State::deprotect_record(ProtectedRecord_DTLS record, + size_t incoming_record_size_limit) { + BOTAN_STATE_CHECK(current_read_epoch_number().is_protected()); + + // RFC 9147 4.2.2 + // When receiving protected DTLS records, the recipient does not have a + // full epoch or sequence number value in the record and so there is some + // opportunity for ambiguity. Because the full sequence number is used to + // compute the per-record nonce and the epoch determines the keys, failure + // to reconstruct these values leads to failure to deprotect the record. + auto epoch = latest_epoch_matching_epoch_hint(record.header.epoch_bits); + if(!epoch.has_value()) { + return std::nullopt; // without a matching epoch, we cannot deprotect the record + } + + record.header.sequence_number = + xor_record_sequence_number(epoch->get(), ciphersuite(), record.payload, record.header.sequence_number); + + // RFC 9147 4.2.2 + // [I]mplementations SHOULD reconstruct the sequence number by computing + // the full sequence number which is numerically closest to one plus the + // sequence number of the highest successfully deprotected record in the + // current epoch. + const uint64_t sequence_number = + reconstruct_full_sequence_number(epoch->get().sequence_number, record.header.sequence_number); + + auto result = Record_Content{ + .type = Record_Type::Invalid, + .sequence_number = sequence_number, + .payload = std::move(record.payload), + .epoch = epoch->get().number, + }; + + try { + deprotect_and_hydrate_content_type(epoch->get(), record.header.serialize(), result, incoming_record_size_limit); + } catch(const Invalid_Authentication_Tag&) { + // RFC 9147 Section 4.5.3 + // Implementations MUST count the number of received packets that fail + // authentication with each key. + epoch->get().deprotection_failures++; + + // RFC 9147 Section 4.5.2 + // Unlike TLS, DTLS is resilient in the face of invalid records + // (e.g., invalid formatting, length, MAC, etc.). In general, + // invalid records SHOULD be silently discarded, thus preserving the + // association [...]. + // + // If deprotection fails (i.e. MAC verification does not check out), we + // silently reject the record. + return std::nullopt; + } + + // -------------------------------------------------------------------------- + // BEYOND THIS LINE WE DEAL WITH AUTHENTICATED DATA. + // Hence, errors are fatal and we throw TLS exceptions with appropriate + // alerts which will terminate the association. + // -------------------------------------------------------------------------- + + // Update "the sequence number of the highest successfully deprotected record" + // (RFC 9147 Section 4.2.2) if the current record's sequence number is higher + // than the previous highest. + epoch->get().sequence_number = std::max(epoch->get().sequence_number, result.sequence_number.value()); + + // RFC 9147 Section 4.1 Figure 5 + // [...] + // + // After deprotection, the record type must be Alert (21), DTLSHandshake (22), + // Application Data (23), Heartbeat (24), or ACK (26). Any other type should + // result in an error and RFC 9846 Section 5 should be enforced: + // + // RFC 9846 Section 5 + // If a TLS implementation receives an unexpected record type, it MUST + // terminate the connection with an "unexpected_message" alert. + if(result.type != Record_Type::Alert && // + result.type != Record_Type::Handshake && // + result.type != Record_Type::ApplicationData && // + result.type != Record_Type::Heartbeat && // + result.type != Record_Type::ACK) { + throw TLS_Exception( + Alert::UnexpectedMessage, + fmt("Deprotected DTLS record had unexpected content type: {}", static_cast(result.type))); + } + + // RFC 9147 6.1 + // Epoch value (3) is used for payloads protected using keys derived from + // the initial [sender]_application_traffic_secret_0 + // + // We thus reject application data records received at the handshake epoch. + if(result.type == Record_Type::ApplicationData && epoch->get().number.is_handshake_traffic()) { + throw TLS_Exception(Alert::UnexpectedMessage, "Can't interleave application and handshake data"); + } + + return annotate_record_type(std::move(result)); +} + +DTLS_Cipher_State::Epoch DTLS_Cipher_State::create_dtls_epoch(EpochNumber epoch_number, + Cipher_Dir direction, + const secure_vector& traffic_secret) { + auto base_epoch = create_epoch(epoch_number, direction, traffic_secret); + auto seqno_key = hkdf_expand_label(traffic_secret, "sn", {}, base_epoch.cipher->minimum_keylength()); + return { + std::move(base_epoch), + std::move(seqno_key), + }; +} + +EpochNumber DTLS_Cipher_State::advance_write_epoch(const secure_vector& traffic_secret, + std::optional epoch_number) { + BOTAN_STATE_CHECK(!current_write_epoch_number().is_exhausted_for_dtls()); + const auto next_epoch_number = epoch_number.value_or(current_write_epoch_number().next()); + m_write_epochs.push_back(create_dtls_epoch(next_epoch_number, Cipher_Dir::Encryption, traffic_secret)); + return next_epoch_number; +} + +EpochNumber DTLS_Cipher_State::advance_read_epoch(const secure_vector& traffic_secret, + std::optional epoch_number) { + BOTAN_STATE_CHECK(!current_read_epoch_number().is_exhausted_for_dtls()); + const auto next_epoch_number = epoch_number.value_or(current_read_epoch_number().next()); + m_read_epochs.push_back(create_dtls_epoch(next_epoch_number, Cipher_Dir::Decryption, traffic_secret)); + return next_epoch_number; +} + +void DTLS_Cipher_State::clear_write_keys() { + m_write_epochs.clear(); +} + +void DTLS_Cipher_State::clear_read_keys() { + m_read_epochs.clear(); +} + +std::optional> DTLS_Cipher_State::latest_epoch_matching_epoch_hint( + uint8_t epoch_hint) { + BOTAN_DEBUG_ASSERT(epoch_hint <= 0b00000011); + + // RFC 9147 Section 4.2.2 + // If the epoch bits match those of the current epoch, then + // implementations SHOULD [attempt to deprotect the record] in the current + // epoch. + // [...] + // After the handshake is complete, if the epoch bits do not match those + // from the current epoch, implementations SHOULD use the most recent past + // epoch which has matching bits [...]. + // + // So we go through our list of available read epochs starting from the + // newest and select the first one that matches the epoch hint. + // + // NOLINTNEXTLINE(modernize-loop-convert): TODO: use std::views::reverse + for(auto it = m_read_epochs.rbegin(); it != m_read_epochs.rend(); ++it) { + if((it->number.index() & 0b00000011) == epoch_hint) { + return *it; + } + } + + // No matching epoch found + return std::nullopt; +} + +void DTLS_Cipher_State::prune_write_epochs_older_than(EpochNumber epoch_number) { + std::erase_if(m_write_epochs, [&](const auto& epoch) { return epoch.number < epoch_number; }); +} + +void DTLS_Cipher_State::prune_read_epochs_older_than(EpochNumber epoch_number) { + std::erase_if(m_read_epochs, [&](const auto& epoch) { return epoch.number < epoch_number; }); +} + +} // namespace Botan::TLS diff --git a/src/lib/tls/dtls13/tls_cipher_state_dtls13.h b/src/lib/tls/dtls13/tls_cipher_state_dtls13.h new file mode 100644 index 00000000000..e1340a907fd --- /dev/null +++ b/src/lib/tls/dtls13/tls_cipher_state_dtls13.h @@ -0,0 +1,125 @@ +/* +* DTLS 1.3 cipher state +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_TLS_DTLS_CIPHER_STATE_13_H_ +#define BOTAN_TLS_DTLS_CIPHER_STATE_13_H_ + +#include +#include +#include +#include + +namespace Botan::TLS { + +class BOTAN_TEST_API DTLS_Cipher_State final : public Cipher_State { + public: + struct Epoch : Cipher_State::Epoch { + secure_vector sequence_number_key; + }; + + public: + DTLS_Cipher_State(Connection_Side side, std::string_view prf_algo); + + ~DTLS_Cipher_State() override; + DTLS_Cipher_State(const DTLS_Cipher_State&) = delete; + DTLS_Cipher_State& operator=(const DTLS_Cipher_State&) = delete; + DTLS_Cipher_State(DTLS_Cipher_State&&) = delete; + DTLS_Cipher_State& operator=(DTLS_Cipher_State&&) = delete; + + /** + * Protect a DTLS record using the traffic secret keys and the current + * sequence number of the latest epoch, or the ones identified by the + * given @p epoch number. This will internally increment the respective + * sequence number. Hence, multiple calls with the same input will not + * produce the same result. + * + * @param type the record type to be protected + * @param payload the record plaintext to be protected in-place + * @param padding_bytes the number of padding zero-bytes to be added + * @param epoch the optional epoch number to use for protection + * @param out the marshalled and protected record (to be sent + * on the wire) is appended to this buffer + * + * @returns the sequence number of the record that was just protected + */ + RecordNumber protect_record(Record_Type type, + std::span payload, + size_t padding_bytes, + secure_vector& out, + std::optional epoch = std::nullopt); + + /** + * Deprotect a DTLS record using the traffic secret keys and the current + * sequence number of the epoch identified by the epoch bits in the record + * header. If that epoch is not available, deprotection will fail and + * std::nullopt will be returned. + * + * @param record the record to be deprotected in-place + * @param incoming_record_size_limit the maximum allowed size for the incoming record + * + * @returns the record payload and deprotected content type + */ + std::optional deprotect_record(ProtectedRecord_DTLS record, size_t incoming_record_size_limit); + + void clear_write_keys() override; + void clear_read_keys() override; + + void prune_write_epochs_older_than(EpochNumber epoch_number); + void prune_read_epochs_older_than(EpochNumber epoch_number); + + private: + Epoch create_dtls_epoch(EpochNumber epoch_number, + Cipher_Dir direction, + const secure_vector& traffic_secret); + + EpochNumber advance_write_epoch(const secure_vector& traffic_secret, + std::optional epoch_number = {}) override; + EpochNumber advance_read_epoch(const secure_vector& traffic_secret, + std::optional epoch_number = {}) override; + + bool has_write_epoch() const override { return !m_write_epochs.empty(); } + + bool has_read_epoch() const override { return !m_read_epochs.empty(); } + + Cipher_State::Epoch& latest_write_epoch() override { + BOTAN_ASSERT_NOMSG(has_write_epoch()); + return m_write_epochs.back(); + } + + const Cipher_State::Epoch& latest_write_epoch() const override { + BOTAN_ASSERT_NOMSG(has_write_epoch()); + return m_write_epochs.back(); + } + + Cipher_State::Epoch& latest_read_epoch() override { + BOTAN_ASSERT_NOMSG(has_read_epoch()); + return m_read_epochs.back(); + } + + const Cipher_State::Epoch& latest_read_epoch() const override { + BOTAN_ASSERT_NOMSG(has_read_epoch()); + return m_read_epochs.back(); + } + + std::optional> latest_epoch_matching_epoch_hint(uint8_t epoch_hint); + + private: + std::vector m_write_epochs; + std::vector m_read_epochs; +}; + +inline DTLS_Cipher_State* as_dtls_cipher_state(Cipher_State* cs) { + auto* dtls_cs = dynamic_cast(cs); + BOTAN_ASSERT_IMPLICATION( + dtls_cs == nullptr, cs == nullptr, "If the cipher state is not a DTLS_Cipher_State, it must be null"); + return dtls_cs; +} + +} // namespace Botan::TLS + +#endif diff --git a/src/lib/tls/dtls13/tls_handshake_layer_dtls13.cpp b/src/lib/tls/dtls13/tls_handshake_layer_dtls13.cpp new file mode 100644 index 00000000000..a2292fee65c --- /dev/null +++ b/src/lib/tls/dtls13/tls_handshake_layer_dtls13.cpp @@ -0,0 +1,299 @@ +/* +* TLS handshake layer implementation for DTLS 1.3 +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Botan::TLS { + +namespace { + +uint32_t load_be24(std::span bytes) { + return make_uint32(0, bytes[0], bytes[1], bytes[2]); +} + +std::array store_be24(uint32_t value) { + BOTAN_ASSERT_NOMSG(value <= 0xFFFFFF); + const auto be = store_be(value); + std::array result{}; + copy_mem(result, std::span{be}.last<3>()); + return result; +} + +struct PreparedHeader { + std::array tls_header_bytes = {}; + std::array dtls_header_bytes = {}; +}; + +struct DTLS_Handshake_Header { + // NOLINTBEGIN(*-non-private-member-variables-in-classes) + + uint8_t msg_type; + uint32_t message_length; + uint16_t message_sequence_number; + uint32_t fragment_offset; + uint32_t fragment_length; + + // NOLINTEND(*-non-private-member-variables-in-classes) + + static DTLS_Handshake_Header parse(std::span bytes) { + return { + .msg_type = bytes[0], + .message_length = load_be24(bytes.subspan<1, 3>()), + .message_sequence_number = load_be(bytes.subspan<4, 2>()), + .fragment_offset = load_be24(bytes.subspan<6, 3>()), + .fragment_length = load_be24(bytes.subspan<9, 3>()), + }; + } + + std::array serialize() const { + return concat(store_be(msg_type), + store_be24(message_length), + store_be(message_sequence_number), + store_be24(fragment_offset), + store_be24(fragment_length)); + } + + HandshakeProtocolHeader serialize_tls_header_portion() const { + return TLS_Handshake_Layer::prepare_header(static_cast(msg_type), message_length); + } +}; + +} // namespace + +DTLS_Handshake_Layer::DTLS_Handshake_Layer(Connection_Side side) : Handshake_Layer(side) {} + +DTLS_Handshake_Layer::~DTLS_Handshake_Layer() = default; + +Handshake_Layer::CopyDataResult DTLS_Handshake_Layer::copy_data(const Policy& policy, + const Handshake_Record& data_from_peer) { + BOTAN_ARG_CHECK(data_from_peer.epoch.has_value(), "Epoch number must be provided for DTLS handshake messages"); + + bool consumed_something = false; + bool skipped_fragment = false; + bool detected_duplicate = false; + + BufferSlicer bs(data_from_peer.payload); + while(!bs.empty()) { + if(bs.remaining() < FRAGMENT_HEADER_LENGTH) { + throw TLS_Exception(AlertType::DecodeError, "Bad lengths in DTLS header"); + } + + const auto header = DTLS_Handshake_Header::parse(bs.take()); + + const auto max_size = policy.maximum_handshake_message_size(); + if(max_size > 0 && header.message_length > max_size) { + throw TLS_Exception(Alert::DecodeError, "msg_len exceeds maximum handshake message size"); + } + + if(header.fragment_offset + header.fragment_length > header.message_length) { + throw TLS_Exception(Alert::IllegalParameter, "Invalid DTLS handshake fragment received"); + } + + if(bs.remaining() < header.fragment_length) { + throw TLS_Exception(AlertType::DecodeError, "Truncated DTLS handshake fragment received"); + } + + // RFC 9147 Section 5.2 + // If the sequence number is less than next_receive_seq, the message + // MUST be discarded. + // + // This is a retransmission of a message we have already consumed. The + // fragment counts as processed (recognized as a duplicate), so it does + // not prevent the containing record from being acknowledged. + if(header.message_sequence_number < m_read_message_seq) { + bs.skip(header.fragment_length); + detected_duplicate = true; + continue; + } + + // RFC 9147 Section 5.2 + // If the sequence number is greater than next_receive_seq, the + // implementation SHOULD queue the message but MAY discard it. + // + // We queue fragments only within a certain window and discard anything + // further in the future. Such fragments cannot be part of the flight we + // are currently waiting for. + // + // Discarded fragments were neither processed nor buffered, hence the + // containing record must not be acknowledged (RFC 9147 Section 7). + if(static_cast(header.message_sequence_number) - m_read_message_seq > MAX_BUFFERED_FUTURE_MESSAGES) { + bs.skip(header.fragment_length); + skipped_fragment = true; + continue; + } + + // TODO: See if we can re-use the reassembly mechanic of DTLS 1.2 that + // handles iterative allocation and fragment memory budgets in a + // secure manner. + // See: https://github.com/randombit/botan/pull/5803 + auto [itr, _] = + m_current_read_message.try_emplace(header.message_sequence_number, + ReassembledMessage{ + .message = + { + .epoch_number = data_from_peer.epoch, + .type = read_handshake_message_type(header.msg_type), + .header = header.serialize_tls_header_portion(), + .payload = SerializedHandshakeMessage(header.message_length), + }, + .received_bytes = bitvector(header.message_length), + .complete = false, + }); + auto& reassembled = itr->second; + + if(reassembled.message.epoch_number != data_from_peer.epoch) { + throw TLS_Exception(Alert::IllegalParameter, + "Detected DTLS handshake message fragments spanning multiple epochs"); + } + + if(reassembled.message.payload.size() != header.message_length || + reassembled.received_bytes.size() != header.message_length || + header.serialize_tls_header_portion() != reassembled.message.header) { + throw TLS_Exception(Alert::IllegalParameter, "Inconsistent values in fragmented DTLS handshake header"); + } + + // RFC 9147 5.5 + // DTLS implementations MUST be able to handle overlapping fragment + // ranges. This allows senders to retransmit handshake messages with + // smaller fragment sizes if the PMTU estimate changes. Senders MUST + // NOT change handshake message bytes upon retransmission. Receivers + // MAY check that retransmitted bytes are identical and SHOULD abort + // the handshake with an "illegal_parameter" alert if the value of a + // byte changes + // + // We choose to not check that retransmitted bytes are identical to + // simplify the implementation. Possible bogus bytes will be recognized + // in the transcript hash check. + + // Advance bs and copy the fragment into the reassembled message + copy_mem(std::span(reassembled.message.payload).subspan(header.fragment_offset, header.fragment_length), + bs.take(header.fragment_length)); + + reassembled.received_bytes.set_range(header.fragment_offset, header.fragment_length); + if(reassembled.received_bytes.all_vartime()) { + reassembled.complete = true; + } + + consumed_something = true; + } + + BOTAN_ASSERT_NOMSG(bs.empty()); + + // If we skipped a fragment without processing it, the entire record must not + // be acknowledged, even if we processed other fragments of the same record. + if(skipped_fragment) { + if(consumed_something) { + return CopyDataResult::ConsumedPartially; + } else { + return CopyDataResult::Discarded; + } + } + + // If no fragment was skipped, and at least one fragment was considered new + // we can acknowledge the record. + if(consumed_something) { + return CopyDataResult::Consumed; + } + + // If no fragments were skipped, and nothing was consumed either, then we + // rejected all contained fragments as duplicates. Such a record may be + // re-acknowledged. + BOTAN_ASSERT_NOMSG(detected_duplicate); + return CopyDataResult::DiscardedDuplicate; +} + +std::optional DTLS_Handshake_Layer::take_next_message() { + auto message = m_current_read_message.find(static_cast(m_read_message_seq)); + if(message == m_current_read_message.end() || !message->second.complete) { + return std::nullopt; + } + + // We are going to emit the next message, and increase the incoming message + // sequence number. Note that this increment might take the sequence number + // above the protocol-mandated maximum of 2^16-1. After that, copy_data() + // will just drop any further incoming handshake messages as duplicates + // because their advertised sequence number is capped at 16-bits. + static_assert(sizeof(m_read_message_seq) > sizeof(uint16_t)); + + auto _ = scoped_cleanup([this, message]() { + m_current_read_message.erase(message); + m_read_message_seq++; + }); + + return std::move(message->second.message); +} + +std::vector DTLS_Handshake_Layer::fragment_message( + Handshake_Type type, + StrongSpan msg_bytes, + uint16_t max_fragment_size, + std::optional first_fragment_max_size) { + BOTAN_ARG_CHECK(max_fragment_size > DTLS_Handshake_Layer::FRAGMENT_HEADER_LENGTH, + "DTLS max fragment size must be larger than header length"); + if(first_fragment_max_size.has_value()) { + BOTAN_ARG_CHECK(first_fragment_max_size > DTLS_Handshake_Layer::FRAGMENT_HEADER_LENGTH, + "DTLS first fragment max size must be larger than header length"); + BOTAN_ARG_CHECK(first_fragment_max_size <= max_fragment_size, + "DTLS first fragment max size must not exceed the general max fragment size"); + } + + // Eventually the increment will take the sequence number above the protocol + // mandated maximum of 2^16-1. After that, future calls to fragment_message() + // will abort the connection. + static_assert(sizeof(m_send_message_seq) > sizeof(uint16_t)); + if(m_send_message_seq > std::numeric_limits::max()) { + throw Invalid_State("Maximum DTLS message sequence number reached"); + } + const auto message_seq = static_cast(m_send_message_seq++); + + std::vector fragments; + + BufferSlicer bs(msg_bytes); + size_t max_bytes_per_fragment = + first_fragment_max_size.value_or(max_fragment_size) - DTLS_Handshake_Layer::FRAGMENT_HEADER_LENGTH; + while(!bs.empty()) { + const auto bytes_in_this_fragment = std::min(bs.remaining(), max_bytes_per_fragment); + const auto header = DTLS_Handshake_Header{ + .msg_type = to_underlying(type), + .message_length = static_cast(msg_bytes.size()), + .message_sequence_number = message_seq, + .fragment_offset = static_cast(msg_bytes.size() - bs.remaining()), + .fragment_length = static_cast(bytes_in_this_fragment), + }; + fragments.push_back( + concat(header.serialize(), bs.take(bytes_in_this_fragment))); + + // All fragments after the first may use the full fragment size budget. + max_bytes_per_fragment = max_fragment_size - DTLS_Handshake_Layer::FRAGMENT_HEADER_LENGTH; + } + BOTAN_ASSERT_NOMSG(!fragments.empty()); + return fragments; +} + +Handshake_Message_13 DTLS_Handshake_Layer::parse_handshake_message(const Message& message, const Policy& policy) const { + switch(message.type) { + case Handshake_Type::HelloVerifyRequest: + // DTLS 1.2 cookie exchange; triggers a client-side downgrade when + // DTLS 1.2 is allowed. Acceptance is enforced by Client_Impl_13. + return Hello_Verify_Request_Shim(message.payload); + default: + return Handshake_Layer::parse_handshake_message(message, policy); + } +} + +} // namespace Botan::TLS diff --git a/src/lib/tls/dtls13/tls_handshake_layer_dtls13.h b/src/lib/tls/dtls13/tls_handshake_layer_dtls13.h new file mode 100644 index 00000000000..ec88c6a9311 --- /dev/null +++ b/src/lib/tls/dtls13/tls_handshake_layer_dtls13.h @@ -0,0 +1,107 @@ +/* +* TLS handshake layer implementation for DTLS 1.3 +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_TLS_HANDSHAKE_LAYER_DTLS13_H_ +#define BOTAN_TLS_HANDSHAKE_LAYER_DTLS13_H_ + +#include +#include +#include + +namespace Botan::TLS { + +/** + * Implementation of the DTLS 1.3 handshake protocol layer + * + * This component transforms bytes received from the peer into bytes + * containing plaintext TLS handshake messages and vice versa. + */ +class BOTAN_TEST_API DTLS_Handshake_Layer final : public Handshake_Layer { + public: + /// The byte length of a DTLS handshake fragment header (RFC 9147 Section 5.2) + static constexpr size_t FRAGMENT_HEADER_LENGTH = 12; + + /** + * RFC 9147 Section 5.2 + * If the sequence number is greater than next_receive_seq, the + * implementation SHOULD queue the message but MAY discard it. + * + * The maximum number of handshake messages beyond the next expected one + * whose fragments are buffered for reassembly. Fragments of messages + * further in the future are discarded. This bounds the memory a peer can + * make us allocate for reassembly and prevents stale reassembly state + * from lingering until the message sequence space eventually reaches it. + * + * The value covers the longest possible flight (ServerHello..Finished + * including client authentication, 6 messages) + */ + static constexpr uint16_t MAX_BUFFERED_FUTURE_MESSAGES = 6; + + explicit DTLS_Handshake_Layer(Connection_Side side); + + DTLS_Handshake_Layer(const DTLS_Handshake_Layer&) = delete; + DTLS_Handshake_Layer(DTLS_Handshake_Layer&&) = delete; + DTLS_Handshake_Layer& operator=(const DTLS_Handshake_Layer&) = delete; + DTLS_Handshake_Layer& operator=(DTLS_Handshake_Layer&&) = delete; + + ~DTLS_Handshake_Layer() override; + + bool has_pending_data() const override { return !m_current_read_message.empty(); } + + CopyDataResult copy_data(const Policy& policy, const Handshake_Record& data_from_peer) override; + + /** + * Splits a handshake message into marshalled fragments, each prefixed + * with a DTLS handshake fragment header. + * + * When @p first_fragment_max_size is provided, the first fragment is + * capped accordingly. All further fragments are capped by + * @p max_fragment_size. This allows callers to fill up space remaining in + * a record that already holds fragments of previous messages. Otherwise, + * all fragments are capped by @p max_fragment_size. + * + * @param type The handshake message type + * @param msg_bytes The serialized handshake message to fragment + * @param max_fragment_size The maximum size of each fragment, including + * the DTLS handshake fragment header + * @param first_fragment_max_size Optional maximum size of the first + * fragment, including the header size. + * + * @returns A vector of marshalled handshake message fragments + */ + std::vector fragment_message( + Handshake_Type type, + StrongSpan msg_bytes, + uint16_t max_fragment_size, + std::optional first_fragment_max_size = std::nullopt); + + private: + TLS_Flavor tls_flavor() const override { return TLS_Flavor::DTLS; } + + std::optional take_next_message() override; + + Handshake_Message_13 parse_handshake_message(const Message& message, const Policy& policy) const override; + + private: + struct ReassembledMessage { + Message message; + bitvector received_bytes; // tracks which bytes of the payload have been received so far + bool complete = false; + }; + + private: + // using 32-bit values to detect sequence number exhaustion + uint32_t m_send_message_seq = 0; + uint32_t m_read_message_seq = 0; + + std::map m_current_read_message; // keyed by message_seq +}; + +} // namespace Botan::TLS + +#endif diff --git a/src/lib/tls/dtls13/tls_record_dtls13.cpp b/src/lib/tls/dtls13/tls_record_dtls13.cpp new file mode 100644 index 00000000000..d04696917f8 --- /dev/null +++ b/src/lib/tls/dtls13/tls_record_dtls13.cpp @@ -0,0 +1,235 @@ +/* +* DTLS record structures of DTLS 1.3 +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include + +#include +#include +#include +#include +#include +#include + +namespace Botan::TLS { + +namespace { + +constexpr uint64_t load_be48(std::span bytes) { + std::array padded_bytes{}; + copy_mem(std::span{padded_bytes}.last<6>(), bytes); + return load_be(padded_bytes); +} + +constexpr std::array store_be48(const uint64_t value) { + const auto padded_bytes = store_be(value); + BOTAN_ARG_CHECK(padded_bytes[0] == 0 && padded_bytes[1] == 0, "Value too large to store in 48 bits"); + + std::array bytes{}; + copy_mem(bytes, std::span{padded_bytes}.last<6>()); + return bytes; +} + +} // namespace + +UnifiedHeader_DTLS UnifiedHeader_DTLS::parse(BufferSlicer& bs, std::optional cid_length) { + if(bs.empty()) { + throw TLS_Exception(AlertType::DecodeError, "DTLS unified header cannot be empty"); + } + + // RFC 9147 Section 4. + // The three high bits of the first byte of the unified header are set to + // 001. [...] + const uint8_t first = bs.take_byte(); + if((first & 0b11100000) != 0b00100000) { + throw TLS_Exception(AlertType::DecodeError, "DTLS unified header must start with 0b001xxxxx"); + } + + UnifiedHeader_DTLS header; + + // RFC 9147 Section 4 Figure 3 + // + // 0 1 2 3 4 5 6 7 + // +-+-+-+-+-+-+-+-+ + // |0|0|1|C|S|L|E E| + // +-+-+-+-+-+-+-+-+ + // + // C: The C bit (0x10) is set if the Connection ID is present. + // S: The S bit (0x08) indicates the size of the sequence number. + // 0 means an 8-bit sequence number, 1 means 16-bit. [...] + // L: The L bit (0x04) is set if the length is present. + // E: The two low bits (0x03) include the low-order two bits of + // the epoch. + const bool cid_bit = (first & 0b00010000) != 0; + const bool seqno_bit = (first & 0b00001000) != 0; + const bool length_bit = (first & 0b00000100) != 0; + header.epoch_bits = first & 0b00000011; + + const size_t expected_length = cid_length.value_or(0) + (seqno_bit ? 2 : 1) + (length_bit ? 2 : 0); + if(bs.remaining() < expected_length) { + throw TLS_Exception(AlertType::DecodeError, "DTLS unified header is truncated"); + } + + // RFC 9147 Section 4 + // If a Connection ID is negotiated, then it MUST be contained in all + // datagrams. + if(cid_bit) { + // RFC 9147 Section 9.1 + // If no CID is negotiated, then the receiver MUST reject any records + // it receives that contain a CID. + if(!cid_length.has_value()) { + throw TLS_Exception(AlertType::DecodeError, "Received protected DTLS record with unexpected CID"); + } + + header.connection_id = bs.copy(cid_length.value()); + } + + if(seqno_bit) { + header.sequence_number = load_be(bs.take<2>()); + } else { + header.sequence_number = bs.take_byte(); + } + + if(length_bit) { + header.length = load_be(bs.take<2>()); + if(bs.remaining() < *header.length) { + throw TLS_Exception(AlertType::DecodeError, "Received protected DTLS record with truncated data"); + } + } + + BOTAN_DEBUG_ASSERT(header.serialized_byte_length() == 1 + expected_length); + + return header; +} + +size_t UnifiedHeader_DTLS::serialized_byte_length() const noexcept { + const size_t connection_id_length = connection_id.has_value() ? connection_id->size() : 0; + const size_t seq_no_length = std::visit([](auto&& arg) -> size_t { return sizeof(arg); }, sequence_number); + const size_t length_length = length.has_value() ? sizeof(decltype(length)::value_type) : 0; + return 1 + connection_id_length + seq_no_length + length_length; +} + +void UnifiedHeader_DTLS::serialize_to(std::span output) const { + const auto expected_length = serialized_byte_length(); + + BOTAN_ARG_CHECK(output.size() >= expected_length, "Output buffer is too small"); + BufferStuffer bs(output.first(expected_length)); + + constexpr uint8_t preamble = 0b00100000; + const uint8_t cid_bit = static_cast(connection_id.has_value()) << 4; + const uint8_t seqno_bit = static_cast(std::holds_alternative(sequence_number)) << 3; + const uint8_t length_bit = static_cast(length.has_value()) << 2; + const uint8_t epoch = epoch_bits & 0b00000011; + + bs.append(preamble | cid_bit | seqno_bit | length_bit | epoch); + + if(connection_id.has_value()) { + bs.append(*connection_id); + } + + std::visit([&](auto&& arg) { bs.append(store_be(arg)); }, sequence_number); + + if(length.has_value()) { + bs.append(store_be(*length)); + } + + BOTAN_DEBUG_ASSERT(bs.full()); +} + +PlaintextHeader_DTLS PlaintextHeader_DTLS::parse(BufferSlicer& bs) { + if(bs.remaining() < DTLS_HEADER_SIZE) { + throw TLS_Exception(AlertType::DecodeError, "Received DTLSPlaintext with truncated header"); + } + + const auto type = static_cast(bs.take_byte()); + const auto legacy_version = Protocol_Version(load_be(bs.take<2>())); + const auto epoch = EpochNumber::create(load_be(bs.take<2>())); + const auto sequence_number = load_be48(bs.take<6>()); + const auto length = load_be(bs.take<2>()); + + if(bs.remaining() < length) { + throw TLS_Exception(AlertType::DecodeError, "Received DTLSPlaintext with truncated payload"); + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + // After this point we're sure that the input buffer contained something that + // roughly resembles a DTLSPlaintext record. Below we're checking the + // semantics of the record header's fields as far as we can. + // + // * Any of the Decode_Errors above would lead to the input datagram being + // discarded by the DTLS_Record_Layer, and + // * Any other errors below would lead to the connection being terminated + // with an alert. + // + + // RFC 9147 Figure 2 DTLSPlaintext + if(epoch.is_protected()) { + throw TLS_Exception(AlertType::IllegalParameter, "Received DTLSPlaintext with epoch != 0"); + } + + // RFC 9846 5.1 + // The length (in bytes) of the following TLSPlaintext.fragment. The + // length MUST NOT exceed 2^14 bytes. An endpoint that receives a record + // that exceeds this length MUST terminate the connection with a + // "record_overflow" alert. + if(MAX_PLAINTEXT_SIZE < length) { + throw TLS_Exception(AlertType::RecordOverflow, "Received DTLSPlaintext with too much plaintext data"); + } + + // RFC 8446 5.1 + // Implementations MUST NOT send zero-length fragments of Handshake + // types, even if those fragments contain padding. + // + // Zero-length fragments of Application Data MAY be sent, as they are + // potentially useful as a traffic analysis countermeasure. + // + // Hence, the payload length must always be non-null. Even for application + // data, the protected payload would contain at least the authentication + // tag and won't ever be empty either. + if(length == 0) { + throw TLS_Exception(AlertType::IllegalParameter, "Received DTLSPlaintext with empty payload"); + } + + // The legacy major version is essentially ossified to 0xFE and anything + // else can be rejected right away. + if(legacy_version.major_version() != 0xFE) { + throw TLS_Exception(AlertType::IllegalParameter, "Received DTLSPlaintext with unexpected record version"); + } + + // RFC 9147 Section 4.1 (cont'd) + // If the first byte is alert(21), handshake(22), or ack(26), the + // record MUST be interpreted as a DTLSPlaintext record. + // + // Additionally, we let ChangeCipherSpec records pass through and + // handle them explicitly in `process_dummy_change_cipher_spec()` + // in TLS::Channel_Impl_13. + if(type != Record_Type::ChangeCipherSpec && // + type != Record_Type::Alert && // + type != Record_Type::Handshake && // + type != Record_Type::ACK) { + throw TLS_Exception(AlertType::UnexpectedMessage, + fmt("Received DTLSPlaintext with unexpected content type: {}", static_cast(type))); + } + + return { + .type = type, + .legacy_version = legacy_version, + .sequence_number = sequence_number, + .length = length, + }; +} + +std::array PlaintextHeader_DTLS::serialize() const { + return concat( + store_be(type), + store_be(legacy_version.version_code()), + store_be(static_cast(EpochNumber::unprotected().index())), // ossified (RFC 9147 Section 4 Figure 2) + store_be48(sequence_number), + store_be(length)); +} + +} // namespace Botan::TLS diff --git a/src/lib/tls/dtls13/tls_record_dtls13.h b/src/lib/tls/dtls13/tls_record_dtls13.h new file mode 100644 index 00000000000..11fa0654235 --- /dev/null +++ b/src/lib/tls/dtls13/tls_record_dtls13.h @@ -0,0 +1,119 @@ +/* +* DTLS record structures of DTLS 1.3 +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_TLS_DTLS_RECORD_13_H_ +#define BOTAN_TLS_DTLS_RECORD_13_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Botan { +class BufferSlicer; +} + +namespace Botan::TLS { + +/** + * Unified header structure for DTLS 1.3 records (RFC 9147 Section 4 Figure 3) + */ +struct BOTAN_TEST_API UnifiedHeader_DTLS { + /// NOLINTBEGIN(*-non-private-member-variables-in-classes) + + /// The two low-order bits of the epoch + uint8_t epoch_bits; + + /// The connection ID (if any) of the record + std::optional connection_id; + + /// The low-order bits of the sequence number (either 8 or 16 bits) + SequenceNumberHint sequence_number; + + /// The (optional) length of the record. If this is not present, the + /// length is assumed to be the remaining bytes in the datagram. + std::optional length; + + /// NOLINTEND(*-non-private-member-variables-in-classes) + + static size_t expected_length(const Policy& policy, std::optional cid_length) { + BOTAN_UNUSED(policy); + + // RFC 9147 Section 4 Figure 3 + constexpr size_t header_byte = 1; + constexpr size_t sequence_number_bytes = 2; // currently hard-coded (TODO: make this configurable via policy) + constexpr size_t length_bytes = 2; // hard-coded (likely forever) + return header_byte + (cid_length.has_value() ? *cid_length : 0) + sequence_number_bytes + length_bytes; + } + + /** + * Parses a unified header from the given @p record_bytes. Typically the + * @p record_bytes will contain more than just the unified header. + * + * @param record_bytes The buffer slicer to parse the unified header from + * @param cid_length The negotiated length of the connection ID or + * std::nullopt if no connection ID was negotiated. + * + * @throws if parsing fails + */ + static UnifiedHeader_DTLS parse(BufferSlicer& record_bytes, std::optional cid_length); + + size_t serialized_byte_length() const noexcept; + void serialize_to(std::span output) const; + + template > + auto serialize() const { + ContainerT output; + output.resize(serialized_byte_length()); + serialize_to(output); + return output; + } +}; + +/** + * Plaintext header of unprotected records "DTLSPlaintext" RFC 9147 4. Figure 2. + * This encapsulates the header fields without the payload. + */ +struct BOTAN_TEST_API PlaintextHeader_DTLS { + /// NOLINTBEGIN(*-non-private-member-variables-in-classes) + + Record_Type type; + Protocol_Version legacy_version; + /* RFC 9147 4. Figure 2: epoch = 0 */ + uint64_t sequence_number; + uint16_t length; + + /// NOLINTEND(*-non-private-member-variables-in-classes) + + /** + * Reads a PlaintextHeader_DTLS from the given @p bs buffer slicer. + */ + static PlaintextHeader_DTLS parse(BufferSlicer& bs); + + std::array serialize() const; +}; + +// RFC 9147 Section 4 Figure 2 "DTLSCiphertext" +struct ProtectedRecord_DTLS { + UnifiedHeader_DTLS header; + secure_vector payload; +}; + +// RFC 9147 Section 4 Figure 2 "DTLSPlaintext" +struct PlaintextRecord_DTLS { + PlaintextHeader_DTLS header; + secure_vector payload; +}; + +} // namespace Botan::TLS + +#endif diff --git a/src/lib/tls/dtls13/tls_record_layer_dtls13.cpp b/src/lib/tls/dtls13/tls_record_layer_dtls13.cpp new file mode 100644 index 00000000000..132c66f9363 --- /dev/null +++ b/src/lib/tls/dtls13/tls_record_layer_dtls13.cpp @@ -0,0 +1,550 @@ +/* +* DTLS record layer implementation for DTLS 1.3 +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Botan::TLS { + +namespace { + +bool protection_desired(DTLS_Cipher_State* cipher_state, std::optional record_epoch) { + // If the user provided a specific epoch, we protect (or not) based on that + // wish. Otherwise, we protect if a cipher_state is provided. + if(record_epoch.has_value()) { + BOTAN_ASSERT_IMPLICATION(record_epoch->is_protected(), + cipher_state != nullptr, + "If the epoch indicates protection, a cipher state must be present"); + return record_epoch->is_protected(); + } else { + return cipher_state != nullptr; + } +} + +} // namespace + +DTLS_Record_Layer::DTLS_Record_Layer(const Policy& policy) : + m_deprotection_failure_limit(policy.dtls_maximum_deprotection_failures()) {} + +bool DTLS_Record_Layer::copy_data(std::span data_from_peer, bool has_cryptographic_association) { + try { + return read_datagram(data_from_peer); + } catch(const TLS_Exception& ex) { + // RFC 9147 Section 4.5.2 + // Unlike TLS, DTLS is resilient in the face of invalid records + // (e.g., invalid formatting, length, MAC, etc.). In general, + // invalid records SHOULD be silently discarded, thus preserving the + // association [...]. + // + // If low-level record parsing failed (i.e., the incoming data looked + // syntactically invalid, e.g. truncated), we discard the datagram + // regardless of the status of the cryptographic association. + // + // When the records were syntactically valid, but semantically invalid + // (e.g., unknown record type, epoch>0 in unprotected record, etc.), we + // might still discard the record, if and only if this connection already + // established a cryptographic association. Otherwise, there is nothing + // to preserve in the sense of the RFC quote above and we rethrow. + // + // All of the above are checks that can be performed without access to the + // cryptographic key material. Any further checks (e.g., MAC verification) + // or checks on the deprotected plaintext are done in `next_record()` and + // beyond. + + if(ex.type() == AlertType::DecodeError) { + // The incoming data was syntactically invalid => discard. + return false; + } + + // Note that `has_cryptographic_association` might turn from true to false + // when we close our write end on the connection. But once we received any + // protected record from the peer, we always treat them as 'authenticated'. + if(has_cryptographic_association || m_authenticated_protected_record_received) { + // Any records recognizable as semantically invalid even before + // deprotection are considered an active attack and discarded. + return false; + } + + // We don't have a cryptographic association yet and the incoming data was + // syntactically valid but semantically invalid. So there is nothing + // to preserve in the sense of the RFC quote above and we abort the + // connection attempt. + throw; + } +} + +bool DTLS_Record_Layer::read_datagram(std::span datagram) { + BufferSlicer bs(datagram); + std::vector records_in_this_datagram; + + // RFC 9147 Section 4.3 + // Multiple DTLS records MAY be placed in a single datagram. Records are + // encoded consecutively. [...] The first byte of the datagram payload + // MUST be the beginning of a record. Records MUST NOT span datagrams. + while(!bs.empty()) { + // RFC 9147 Section 4.1 + // If the [...] leading bits of the first byte are 001 [...] the + // implementation MUST process the record as DTLSCiphertext; the true + // content type will be inside the protected portion. + const bool is_protected_record = (bs.peek_byte() & 0b11100000) == 0b00100000; + if(is_protected_record) { + records_in_this_datagram.push_back(read_protected_record(bs)); + } else { + records_in_this_datagram.push_back(read_plaintext_record(bs)); + } + } + + BOTAN_DEBUG_ASSERT(bs.empty()); + + // Only commit the records found in the passed-in datagram once the entire + // datagram has been successfully processed. This way, records from a + // datagram that included an invalid record (e.g., due to decoding error) + // will not be added to the read buffer. + m_incoming_records.insert(m_incoming_records.end(), + std::make_move_iterator(records_in_this_datagram.begin()), + std::make_move_iterator(records_in_this_datagram.end())); + + return true; +} + +PlaintextRecord_DTLS DTLS_Record_Layer::read_plaintext_record(BufferSlicer& bs) { + auto header = PlaintextHeader_DTLS::parse(bs); + if(bs.remaining() < header.length) { + throw TLS_Exception(AlertType::DecodeError, "Received DTLSPlaintext with truncated payload"); + } + + return { + .header = header, + .payload = bs.copy_as_secure_vector(header.length), + }; +} + +ProtectedRecord_DTLS DTLS_Record_Layer::read_protected_record(BufferSlicer& bs) { + auto unified_header = UnifiedHeader_DTLS::parse(bs, std::nullopt /* CID NYI */); + + // RFC 9147 Section 4.3 + // The length field from DTLS records containing that field can be + // used to determine the boundaries between records. The final + // record in a datagram can omit the length field. + // + // RFC 9147 Section 4. + // The length field MAY be omitted [...], which means that the + // record consumes the entire rest of the datagram in the lower + // level transport. + const auto fragment_length = unified_header.length.value_or(checked_cast_to(bs.remaining())); + + // RFC 9147 Section 4.2.3 + // [The sequence number deprotection procedure] requires the ciphertext + // length to be at least 16 bytes. Receivers MUST reject shorter records + // as if they had failed deprotection. + // + // We throw a DecodeError here, which will lead to the datagram being + // discarded by the DTLS_Record_Layer (as if it failed deprotection). + if(fragment_length < 16) { + throw TLS_Exception(Alert::DecodeError, "Received an encrypted record that is too short"); + } + + // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + // After this point we're sure that the input buffer contained something that + // roughly resembles a DTLSCiphertext record. Below we're checking the + // semantics of the record header's fields as far as we can. + // + // * Any of the Decode_Errors above would lead to the input datagram being + // discarded by the DTLS_Record_Layer, and + // * Any other errors below would lead to the connection being terminated + // with an alert. + // + + // RFC 8449 Section 4 + // a DTLS endpoint that receives a record larger than its advertised + // limit MAY either generate a fatal "record_overflow" alert or + // discard the record. + // + // We reject records that would exceed the maximum allowed size after + // deprotection for sure (the AEAD can only add up to 255 bytes). + if(fragment_length + unified_header.serialized_byte_length() > + incoming_record_size_limit() + MAX_AEAD_EXPANSION_SIZE_TLS13) { + throw TLS_Exception(Alert::RecordOverflow, "Received a datagram that exceeds maximum size"); + } + + return { + .header = std::move(unified_header), + .payload = bs.copy_as_secure_vector(fragment_length), + }; +} + +DTLS_Record_Layer::IncomingRecord DTLS_Record_Layer::next_incoming_record() { + BOTAN_STATE_CHECK(!m_incoming_records.empty()); + + auto next_record = std::move(m_incoming_records.front()); + m_incoming_records.erase(m_incoming_records.begin()); + return next_record; +} + +Replay_Window_13& DTLS_Record_Layer::replay_window_for_epoch(EpochNumber epoch) { + auto it = m_replay_windows.find(epoch); + if(it == m_replay_windows.end()) { + it = m_replay_windows.emplace(epoch, Replay_Window_13()).first; + } + return it->second; +} + +Record_Layer::ReadResult DTLS_Record_Layer::next_record(Cipher_State* cipher_state) { + auto* cs = as_dtls_cipher_state(cipher_state); + + while(!m_incoming_records.empty()) { + const auto current_read_epoch = cs != nullptr ? cs->current_read_epoch_number() : EpochNumber::unprotected(); + + auto maybe_next_record = std::visit( // + overloaded{ + [&](PlaintextRecord_DTLS record) -> std::optional { + // RFC 9147 4.2.1 + // Implementations SHOULD discard records from earlier epochs + // [...]. + // + // RFC 9147 7. + // During the handshake, ACK records MUST be sent with an + // epoch which is equal to or higher than the record which is + // being acknowledged. + // + // Until a protected record from the peer was successfully + // deprotected, a plaintext ACK is therefore still legitimate, + // e.g. an ACK of (fragmented) ServerHello records. Afterwards, + // we no longer accept plaintext ACKs. + const bool during_the_handshake = !current_read_epoch.is_application_traffic(); + const bool peer_never_sent_encrypted_records = !m_authenticated_protected_record_received; + const bool is_tolerated_plaintext_ack = + record.header.type == Record_Type::ACK && during_the_handshake && peer_never_sent_encrypted_records; + if(current_read_epoch.is_protected() && !is_tolerated_plaintext_ack) { + return std::nullopt; + } + + // The unprotected sequence number of received records is tracked + // rudimentarily. We pass the highest seen sequence number to the + // DTLS 1.2 implementation during downgrade. + m_unprotected_read_seq_no = std::max(m_unprotected_read_seq_no, record.header.sequence_number); + + return annotate_record_type({ + .type = record.header.type, + .sequence_number = record.header.sequence_number, + .payload = std::move(record.payload), + .epoch = EpochNumber::unprotected(), // ossified (RFC 9147 Section 4 Figure 2) + }); + }, + [&](ProtectedRecord_DTLS record) -> std::optional { + // RFC 9147 Section 4.5.2 + // In general, invalid records SHOULD be silently discarded + // [...]. + // + // We received a protected record but don't have a cryptographic + // association yet, so we can't deprotect it. + if(current_read_epoch.is_unprotected()) { + return std::nullopt; + } + + return cs->deprotect_record(std::move(record), incoming_record_size_limit()); + }, + }, + next_incoming_record()); + + if(!maybe_next_record.has_value()) { + // RFC 9147 Section 4.5.3 + // Implementations MUST count the number of received packets that + // fail authentication with each key. If the number of packets that + // fail authentication exceeds a limit that is specific to the AEAD + // in use, an implementation SHOULD immediately close the connection. + // + // The deprotection failure counter only grows on deprotection + // failures. Hence, this check is a no-op for records discarded for + // other reasons (e.g. replays). + if(cs != nullptr && cs->current_read_epoch_deprotection_failures() > m_deprotection_failure_limit) { + throw TLS_Exception(Alert::BadRecordMac, "Too many deprotection failures in current read epoch"); + } + } else { + std::visit( + [&](const auto& record) { + BOTAN_DEBUG_ASSERT(record.epoch.has_value() && record.sequence_number.has_value()); + + // RFC 9147 Section 4.5.1 + // For each received record, the receiver MUST verify that the + // record contains a sequence number that does not duplicate the + // sequence number of any other record received in that epoch during + // the lifetime of the association. This check SHOULD happen after + // deprotecting the record; otherwise, the record discard might + // itself serve as a timing channel for the record number. + auto& window = replay_window_for_epoch(record.epoch.value()); + if(!window.accept(record.sequence_number.value())) { + maybe_next_record.reset(); + } else if(record.epoch->is_protected()) { + // A protected record that was successfully deprotected and + // passed the replay window proves that the peer holds keys. + m_authenticated_protected_record_received = true; + } + }, + *maybe_next_record); + } + + // If `maybe_next_record` is still set, we return it. If it is not set, + // the record might either have failed deprotection or was replayed, in + // which case we discard it and continue with the next record. + if(maybe_next_record.has_value()) { + return generalize_to(std::move(maybe_next_record).value()); + } + } + + return BytesNeeded(0); +} + +RecordNumber DTLS_Record_Layer::prepare_record(Record_Type type, + std::span payload, + const Policy& policy, + Cipher_State* cipher_state, + secure_vector& out, + std::optional epoch) { + auto* cs = as_dtls_cipher_state(cipher_state); + + const bool protect = protection_desired(cs, epoch); + + // RFC 8449 4. + // When the "record_size_limit" extension is negotiated, an endpoint + // MUST NOT generate a protected record with plaintext that is larger + // than the RecordSizeLimit value it receives from its peer. + // Unprotected messages are not subject to this limit. + // + // The record size limit covers the complete TLSInnerPlaintext, i.e. the + // payload plus the inner content type byte (and any padding). + if(protect) { + BOTAN_ARG_CHECK(payload.size() + CONTENT_TYPE_TAG_LENGTH <= outgoing_record_size_limit(), + "Record payload exceeds the negotiated record size limit"); + } + + // RFC 9846 5.1 + // The length MUST NOT exceed 2^14 bytes. + // + // We deliberately do not check against record_payload_size_limit() here, + // because this would take the configured MTU into account. We won't stop the + // user from sending larger records than their configuration allows. + BOTAN_ASSERT_NOMSG(payload.size() <= MAX_PLAINTEXT_SIZE); + BOTAN_ASSERT_NOMSG(type != Record_Type::ChangeCipherSpec); + + // RFC 9846 5.1 + // Application Data messages are always protected. + BOTAN_ASSERT_IMPLICATION(type == Record_Type::ApplicationData, + cs != nullptr, + "Application Data records MUST NOT be written to the wire unprotected"); + + // RFC 9846 5.1 + // Implementations MUST NOT send zero-length fragments of Handshake types, + // even if those fragments contain padding. [...] a record with an Alert + // type MUST contain exactly one message. [...] Zero-length fragments of + // Application Data [...] MAY be sent, as they are potentially useful as a + // traffic analysis countermeasure. + BOTAN_ASSERT_IMPLICATION(payload.empty(), + type == Record_Type::ApplicationData, + "Zero-length fragments are only allowed for Application Data"); + + if(!protect) { + // RFC 9147 Section 4 (3.) + // The sequence number is set to be the low order 48 bits of the 64 bit + // sequence number. Plaintext records MUST NOT be sent with sequence + // numbers that would exceed 2^48-1, so the upper 16 bits will always be 0. + BOTAN_ASSERT_NOMSG(m_unprotected_write_seq_no < (uint64_t(1) << 48) - 1); + + const auto write_seq_no = m_unprotected_write_seq_no++; + + const auto header = PlaintextHeader_DTLS{ + .type = type, + .legacy_version = Protocol_Version::DTLS_V12, // TODO: perhaps use V10 for first message (compatibility) + // .epoch = 0 (Unprotected), // ossified (RFC 9147 Section 4 Figure 2) + .sequence_number = write_seq_no, + .length = static_cast(payload.size()), + }; + + append(out, header.serialize()); + append(out, payload); + + return { + .epoch = EpochNumber::unprotected(), + .sequence_number = write_seq_no, + }; + } else { + BOTAN_DEBUG_ASSERT(!epoch.has_value() || epoch->is_protected()); + + // The payload's fitness for the negotiated record size limit was checked + // at the top of this function. + const size_t pt_size_with_type_tag = payload.size() + CONTENT_TYPE_TAG_LENGTH; + const size_t max_record_size = outgoing_record_size_limit(); + + // Don't even bother consulting the policy if we already filled the + // record fully, because then we can't add any padding anyway. + // If the user requests more padding than we can actually add, we will + // truncate the padding to fill up the record entirely. + const size_t padding_length = + (pt_size_with_type_tag < max_record_size) + ? std::min(policy.record_padding_bytes(pt_size_with_type_tag), max_record_size - pt_size_with_type_tag) + : 0; + BOTAN_ASSERT_NOMSG(pt_size_with_type_tag + padding_length <= max_record_size); + + return cs->protect_record(type, payload, padding_length, out, epoch); + } +} + +RecordNumber DTLS_Record_Layer::prepare_handshake_record(PackedHandshakeMessageFragments packed_fragments, + secure_vector& out, + const Policy& policy, + Cipher_State* cipher_state, + std::optional epoch) { + BOTAN_ASSERT_NOMSG(packed_fragments.size() <= record_payload_size_limit(policy, cipher_state, epoch)); + + const auto record_number = + prepare_record(Record_Type::Handshake, packed_fragments, policy, cipher_state, out, epoch); + m_unacked_outgoing_handshake_records.push_back({ + .record_numbers = {record_number}, + .packed_fragments = std::move(packed_fragments), + }); + + return record_number; +} + +std::vector DTLS_Record_Layer::prepare_unacknowledged_records(const Policy& policy, + Cipher_State* cipher_state) { + std::vector prepared_records; + prepared_records.reserve(m_unacked_outgoing_handshake_records.size()); + + for(auto& record_info : m_unacked_outgoing_handshake_records) { + auto& out = prepared_records.emplace_back(); + record_info.record_numbers.push_back(prepare_record(Record_Type::Handshake, + record_info.packed_fragments, + policy, + cipher_state, + out.get(), + record_info.record_numbers.back().epoch)); + } + + return prepared_records; +} + +uint16_t DTLS_Record_Layer::record_payload_size_limit(const Policy& policy, + Cipher_State* cipher_state, + std::optional epoch) const { + auto* cs = as_dtls_cipher_state(cipher_state); + + const auto mtu = policy.dtls_default_mtu(); + const auto overhead = [&]() -> size_t { + if(!protection_desired(cs, epoch)) { + return DTLS_HEADER_SIZE; + } else { + constexpr size_t content_type_length = 1; + const size_t tag_length = cs->encrypt_output_length(0); + return UnifiedHeader_DTLS::expected_length(policy, std::nullopt /* TODO: support CID */) + + content_type_length + tag_length; + } + }(); + + // Cap the record payload at the specified hard limit if the user-provided MTU + // is exorbitantly large. + BOTAN_ARG_CHECK(mtu > overhead, "MTU must be larger than the record overhead"); + + // RFC 8449 4. + // When the "record_size_limit" extension is negotiated, an endpoint + // MUST NOT generate a protected record with plaintext that is larger + // than the RecordSizeLimit value it receives from its peer. + // Unprotected messages are not subject to this limit. + // + // Note that the record size limit applies to the complete TLSInnerPlaintext, + // i.e. including the inner content type byte (and any padding). Hence, the + // payload capacity of a protected record is one byte below the negotiated + // limit. Unprotected records are limited by the protocol's maximum plaintext + // size alone. + const size_t negotiated_size_limit = + protection_desired(cs, epoch) ? outgoing_record_size_limit() - CONTENT_TYPE_TAG_LENGTH : MAX_PLAINTEXT_SIZE; + + return static_cast(std::min({MAX_PLAINTEXT_SIZE, negotiated_size_limit, mtu - overhead})); +} + +void DTLS_Record_Layer::clear_read_buffer() { + m_incoming_records.clear(); +} + +void DTLS_Record_Layer::acknowledge_handshake_record(RecordNumber record_number, const Policy& policy) { + m_record_numbers_to_ack.emplace_back(record_number); + + // RFC 9147 Section 7.1 + // If space is limited, implementations SHOULD favor including records + // which have not yet been acknowledged. + // + // Hence, we retain only the most recently received record numbers. + if(m_record_numbers_to_ack.size() > policy.dtls_maximum_queued_acknowledgements()) { + m_record_numbers_to_ack.erase(m_record_numbers_to_ack.begin()); + } +} + +bool DTLS_Record_Layer::has_outstanding_acknowledgements() const { + return !m_record_numbers_to_ack.empty(); +} + +ACKs DTLS_Record_Layer::acknowledgements() const { + return ACKs(m_record_numbers_to_ack); +} + +ACK_Effect DTLS_Record_Layer::handle_acknowledgements(const ACKs& acks) { + const auto unacked_before = m_unacked_outgoing_handshake_records.size(); + + std::erase_if(m_unacked_outgoing_handshake_records, [&](const auto& record_info) { + return std::any_of( + acks.record_numbers().begin(), acks.record_numbers().end(), [&](const auto& acked_record_number) { + return value_exists(record_info.record_numbers, acked_record_number); + }); + }); + + if(m_unacked_outgoing_handshake_records.size() == unacked_before) { + return ACK_Effect::ACKed_Nothing; + } + + return m_unacked_outgoing_handshake_records.empty() // + ? ACK_Effect::ACKed_Everything + : ACK_Effect::ACKed_Something; +} + +bool DTLS_Record_Layer::has_unacknowledged_record(const RecordNumber& record_number) const { + return std::any_of(m_unacked_outgoing_handshake_records.begin(), + m_unacked_outgoing_handshake_records.end(), + [&](const auto& record_info) { return value_exists(record_info.record_numbers, record_number); }); +} + +bool DTLS_Record_Layer::has_unacknowledged_records() const { + return !m_unacked_outgoing_handshake_records.empty(); +} + +void DTLS_Record_Layer::clear_resend_buffer() { + m_unacked_outgoing_handshake_records.clear(); +} + +void DTLS_Record_Layer::clear_outstanding_acknowledgements() { + m_record_numbers_to_ack.clear(); +} + +void DTLS_Record_Layer::prune_replay_windows_older_than(EpochNumber epoch) { + m_replay_windows.erase(m_replay_windows.begin(), m_replay_windows.lower_bound(epoch)); +} + +} // namespace Botan::TLS diff --git a/src/lib/tls/dtls13/tls_record_layer_dtls13.h b/src/lib/tls/dtls13/tls_record_layer_dtls13.h new file mode 100644 index 00000000000..861ad94889e --- /dev/null +++ b/src/lib/tls/dtls13/tls_record_layer_dtls13.h @@ -0,0 +1,206 @@ +/* +* TLS record layer implementation for DTLS 1.3 +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_TLS_RECORD_LAYER_DTLS13_H_ +#define BOTAN_TLS_RECORD_LAYER_DTLS13_H_ + +#include +#include +#include +#include +#include +#include + +namespace Botan { + +class BufferSlicer; + +} + +namespace Botan::TLS { + +class Callbacks; +class Policy; + +/** + * Indicates the effect of applying an ACK message to the list of + * unacknowledged outgoing handshake records. + */ +enum class [[nodiscard]] ACK_Effect : uint8_t { + /// No outstanding record was acknowledged, e.g., because the ACK was + /// redundant, referenced unknown records, or nothing was outstanding. + ACKed_Nothing, + + /// At least one outstanding record was acknowledged, but others remain. + ACKed_Something, + + /// All previously outstanding records were acknowledged. + ACKed_Everything, +}; + +/** + * Implementation of the DTLS 1.3 record protocol layer + * + * This component transforms bytes received from the peer into bytes + * containing plaintext TLS messages and vice versa. + */ +class BOTAN_TEST_API DTLS_Record_Layer final : public Record_Layer { + public: + using IncomingRecord = std::variant; + + struct HandshakeRecordInfo /* NOLINT(*-member-init) */ { + std::vector record_numbers; // Includes numbers of previous transmissions + PackedHandshakeMessageFragments packed_fragments; + }; + + public: + explicit DTLS_Record_Layer(const Policy& policy); + + bool copy_data(std::span data_from_peer, bool has_cryptographic_association) override; + + ReadResult next_record(Cipher_State* cipher_state = nullptr) override; + + RecordNumber prepare_record(Record_Type type, + std::span payload, + const Policy& policy, + Cipher_State* cipher_state, + secure_vector& out, + std::optional epoch = std::nullopt) override; + + /** + * Prepares a single handshake record from a payload containing one or + * more packed handshake message fragments and tracks the record for + * potential retransmission. + * + * @param packed_fragments the marshalled handshake message fragments + * to be packed into the record + * @param out the output buffer to write the record into + * @param policy the policy to use for this record + * @param cipher_state the cipher state to protect the record with + * @param epoch the epoch to send the record in; if not + * provided, the current write epoch is used + */ + RecordNumber prepare_handshake_record(PackedHandshakeMessageFragments packed_fragments, + secure_vector& out, + const Policy& policy, + Cipher_State* cipher_state, + std::optional epoch = std::nullopt); + + /** + * Re-prepares all records that are currently not acknowledged by the + * peer. Acknowledgements could either be explicit (via ACK records) or + * implicit (via flight state progress). + * + * @note This call is relevant for DTLS only. + * + * @returns a vector of ready-to-send records re-prepared in the + * respective epoch of their first transmission. + */ + std::vector prepare_unacknowledged_records(const Policy& policy, Cipher_State* cipher_state); + + /** + * Like the overload above, but determines the record overhead from the + * protection epoch the record will be sent in rather than from the mere + * presence of a cipher state. This matters when a flight contains both + * unprotected (epoch 0) and protected messages: the unprotected records + * may carry slightly more payload. + */ + uint16_t record_payload_size_limit(const Policy& policy, + Cipher_State* cipher_state, + std::optional epoch = std::nullopt) const override; + + void clear_read_buffer() override; + + /** + * Queues an acknowledgement for a handshake record received from the + * peer, to be emitted with the next outgoing ACK record. + * + * RFC 9147 Section 7 + * The ACK message is used by an endpoint to indicate which handshake + * records it has received and processed from the other side. [...] + * Implementations MUST NOT acknowledge records containing handshake + * messages or fragments which have not been processed or buffered. + * Otherwise, deadlock can ensue. + * + * Hence, this must be called only after the record's content was + * successfully passed to and accepted by the handshake layer. Records + * that don't carry handshake messages (most notably application data) + * are never acknowledged. + */ + void acknowledge_handshake_record(RecordNumber record_number, const Policy& policy); + + /** + * @returns true if at least one received handshake record is currently + * queued for acknowledgement + */ + bool has_outstanding_acknowledgements() const; + + /** + * Generates a serialized ACK message containing all records that were + * successfully received and processed by the record layer. This list is + * cleared whenever progress is made in the handshake state machine (see + * `clear_outstanding_acknowledgements()`). + */ + ACKs acknowledgements() const; + + /** + * Processes an incoming ACK message and removes all acknowledged records + * from the list of unacknowledged outgoing handshake records. + * + * @returns the effect the ACK had on the list of unacknowledged records + */ + ACK_Effect handle_acknowledgements(const ACKs& ack_payload); + + bool has_unacknowledged_record(const RecordNumber& record_number) const; + bool has_unacknowledged_records() const; + + void clear_resend_buffer(); + void clear_outstanding_acknowledgements(); + void prune_replay_windows_older_than(EpochNumber epoch); + + std::optional epoch0_sequence_numbers() const noexcept override { + return Epoch0_SequenceNumbers{ + .read = m_unprotected_read_seq_no, + .write = m_unprotected_write_seq_no, + }; + } + + private: + bool read_datagram(std::span datagram); + + PlaintextRecord_DTLS read_plaintext_record(BufferSlicer& bs); + ProtectedRecord_DTLS read_protected_record(BufferSlicer& bs); + + IncomingRecord next_incoming_record(); + + Replay_Window_13& replay_window_for_epoch(EpochNumber epoch); + + private: + std::deque m_incoming_records; + std::vector m_unacked_outgoing_handshake_records; + + std::map m_replay_windows; + size_t m_deprotection_failure_limit; + + /// epoch=0 outgoing record sequence number (all other epochs are tracked in Cipher_State) + uint64_t m_unprotected_write_seq_no = 0; + + /// epoch=0 incoming record sequence number (all other epochs are tracked in Cipher_State) + uint64_t m_unprotected_read_seq_no = 0; + + /// Set once a protected record from the peer was successfully deprotected + /// and accepted by the replay window. Used to decide whether plaintext ACK + /// records are still tolerated. + bool m_authenticated_protected_record_received = false; + + std::vector m_record_numbers_to_ack; +}; + +} // namespace Botan::TLS + +#endif diff --git a/src/lib/tls/dtls13/tls_timer_dtls13.h b/src/lib/tls/dtls13/tls_timer_dtls13.h new file mode 100644 index 00000000000..13dbf545f48 --- /dev/null +++ b/src/lib/tls/dtls13/tls_timer_dtls13.h @@ -0,0 +1,439 @@ +/* +* DTLS timer helpers +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_TLS_TIMER_DTLS13_H_ +#define BOTAN_TLS_TIMER_DTLS13_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Botan::TLS { + +class Callbacks; + +/** + * A convenience wrapper for Callbacks::tls_register_deferred_operation() that + * allows scheduling an asynchronous operation that is run exactly once after + * a specified delay. + * + * If the application invokes the registered operation before the deadline, the + * timer is re-armed for the remaining time. A duplicate invocation of the same + * registered operation is a no-op. + */ +class SingleshotTimer final { + public: + using DeferredOperation = std::function; + + private: + /** + * Tracks a single registration of a deferred operation. This is needed to + * avoid re-arming a deferred operation more than once if an application + * calls it prematurely multiple times, and to ensure the user operation + * runs at most once across the whole registration chain. + */ + struct Registration { + bool consumed = false; + }; + + /** + * This Token is owned by the SingleshotTimer object and shared with the + * cancellable deferred operation as a weak_ptr. If the Token is destroyed + * before the deferred operation is executed, the operation will act as a + * no-op. + * + * If the using application (accidentally) calls the deferred operation + * more than once on the same SingleshotTimer object it will still only be + * executed once. If the Token is destroyed before the deferred operation + * is executed, the operation will not be executed at all. + */ + struct Token { + uint64_t deadline_ms = 0; + std::shared_ptr registration; + }; + + using TokenHandle = std::variant, std::shared_ptr>; + + explicit SingleshotTimer(std::shared_ptr token) : m_token(std::move(token)) {} + + static std::shared_ptr register_deferred_operation(const std::shared_ptr& callbacks, + const TokenHandle& token_handle, + uint64_t delay_ms, + DeferredOperation operation) { + auto registration = std::make_shared(); + + std::visit( + [&](auto&& handle) mutable { + callbacks->tls_register_deferred_operation(delay_ms, + [weak_cb = std::weak_ptr(callbacks), + handle, + registration, + operation = std::move(operation)]() mutable { + run_or_rearm( + weak_cb, handle, registration, std::move(operation)); + }); + }, + token_handle); + + return registration; + } + + static uint64_t remaining(const Token& token, Callbacks& callbacks) { + const auto now = callbacks.tls_current_monotonic_clock_ms(); + const auto deadline = token.deadline_ms; + + if(deadline <= now) { + return 0; + } else { + return deadline - now; + } + } + + static void run_or_rearm(const std::weak_ptr& weak_callbacks, + const TokenHandle& token_handle, + const std::shared_ptr& registration, + DeferredOperation operation) { + // If the deferred operation was called previously this becomes a no-op + // so that timers aren't re-armed multiple times and the user operation + // is only executed exactly once. + if(registration->consumed) { + return; + } + + // If our Callbacks object is gone, we have to assume that the deferred + // operation survived the underlying TLS channel and its dependencies. + const auto cb = weak_callbacks.lock(); + if(!cb) { + return; + } + + // The `token_handle` might be a shared or a weak pointer. In the latter + // case, the Token might have been destroyed already (timer cancelled), + // and we have to treat this as a no-op. + std::shared_ptr token = + std::visit(overloaded{ + [&](const std::weak_ptr& weak_token) { return weak_token.lock(); }, + [&](const std::shared_ptr& shared_token) { return shared_token; }, + }, + token_handle); + if(!token) { + return; + } + + // We are now past the sanity checks and it is time to act. In any case + // this particular registration is now being consumed. + registration->consumed = true; + + const auto remaining_ms = remaining(*token, *cb); + if(remaining_ms > DTLS_RETRANSMISSION_TIMER_FUDGE) { + // The timer was called pre-maturely. We re-arm it with a new + // registration for the remaining time until the deadline. + token->registration = register_deferred_operation(cb, token_handle, remaining_ms, std::move(operation)); + } else { + // The timer has expired and we can execute the deferred operation. + // No new registration is created, because the operation served + // its purpose and is now retired. + token->registration.reset(); + operation(); + } + } + + static std::shared_ptr make_token(const std::shared_ptr& callbacks, + std::chrono::milliseconds delay) { + auto token = std::make_shared(); + const uint64_t now_ms = callbacks->tls_current_monotonic_clock_ms(); + token->deadline_ms = now_ms + static_cast(delay.count()); + return token; + } + + public: + SingleshotTimer() = default; + ~SingleshotTimer() = default; + + SingleshotTimer(const SingleshotTimer&) = delete; + SingleshotTimer& operator=(const SingleshotTimer&) = delete; + SingleshotTimer(SingleshotTimer&&) = default; + SingleshotTimer& operator=(SingleshotTimer&&) = default; + + public: + /** + * Start a deferred operation that will be executed after the given delay. + * This operation cannot be cancelled. + */ + static void start_detached(const std::shared_ptr& callbacks, + std::chrono::milliseconds delay, + DeferredOperation operation) { + auto token = make_token(callbacks, delay); + token->registration = register_deferred_operation(callbacks, token, delay.count(), std::move(operation)); + } + + /** + * Start a deferred operation that can be cancelled using the returned + * SingleshotTimer object. The operation will be executed after the given + * delay unless the SingleshotTimer object is destroyed or cancel() is + * called before the operation is executed. + */ + [[nodiscard]] static SingleshotTimer start(const std::shared_ptr& callbacks, + std::chrono::milliseconds delay, + DeferredOperation operation) { + auto token = make_token(callbacks, delay); + token->registration = + register_deferred_operation(callbacks, std::weak_ptr(token), delay.count(), std::move(operation)); + return SingleshotTimer(std::move(token)); + } + + /// Cancel the deferred operation if it has not yet been executed. + void cancel() { m_token.reset(); } + + /// @returns true if the deferred operation is currently armed and was + /// not yet executed; false otherwise + bool armed() const { return m_token != nullptr && m_token->registration != nullptr; } + + // NOLINTNEXTLINE(*-explicit-conversions) + operator bool() const { return armed(); } + + /** + * @returns the remaining waiting time or std::nullopt if not armed + * + * Note that this might return 0ms if the timer is armed and the deadline + * has been reached, but the deferred operation has not yet been executed. + */ + std::optional remaining(Callbacks& callbacks) const { + if(!armed()) { + return std::nullopt; + } + + BOTAN_DEBUG_ASSERT(m_token != nullptr); + return std::chrono::milliseconds(remaining(*m_token, callbacks)); + } + + private: + std::shared_ptr m_token; +}; + +/** + * DTLS retransmission timer implementing the schedule of RFC 9147 5.8.2: + * the timeout starts at the policy's initial value and doubles with each + * retransmission, capped at the policy's maximum. Additionally, a "flight + * timeout" can be configured to bound the waiting time for progress from the + * peer with a blanket timeout. + * + * Blanket flight timeouts are especially useful in DTLS 1.3 when the peer fully + * acknowledged our flight (either explicitly via ACKs or implicitly by + * responding with a partial flight) but then does not complete its flight. + * + * The user can cancel and restart the timer as needed. The retransmission timer + * can be cancelled without cancelling the blanket flight timeout in exactly the + * scenario described above. If the timer object is destroyed, both timers are + * automatically cancelled. + */ +class RetransmissionTimer final { + public: + using DeferredOperation = std::function; + using TimeoutHandler = std::function; + + private: + /** + * The retransmission timer keeps its state in a shared_ptr so that + * the deferred operation can hold a weak_ptr to this state object instead + * of the actual RetransmissionTimer object. The Token's lifetime is bound + * to the RetransmissionTimer's lifetime and not the deferred operation. + * + * Because the RetransmissionTimer implements an exponential backoff, the + * deferred operation can re-schedule itself using only the Token's state + * without needing to access the RetransmissionTimer object. + */ + struct Token { + const std::chrono::milliseconds initial_timeout; + const std::chrono::milliseconds max_timeout; + const std::optional flight_timeout; + const std::optional max_retransmissions; + const std::shared_ptr callbacks; + + DeferredOperation on_retransmission; + TimeoutHandler on_timeout; + size_t retransmissions; + std::chrono::milliseconds next_timeout; + SingleshotTimer retransmission_timer; + SingleshotTimer flight_timer; + }; + + static std::optional get_flight_timeout(const Policy& policy) { + // TODO(C++23): std::optional::transform + if(const auto timeout = policy.dtls_flight_timeout()) { + return std::chrono::milliseconds(*timeout); + } + return std::nullopt; + } + + public: + RetransmissionTimer(const Policy& policy, std::shared_ptr callbacks) : + m_token(std::make_shared(Token{ + .initial_timeout = std::chrono::milliseconds(policy.dtls_initial_timeout()), + .max_timeout = std::chrono::milliseconds(policy.dtls_maximum_timeout()), + .flight_timeout = get_flight_timeout(policy), + .max_retransmissions = policy.dtls_maximum_retransmissions(), + .callbacks = std::move(callbacks), + .on_retransmission = {}, + .on_timeout = {}, + .retransmissions = 0, + .next_timeout = std::chrono::milliseconds(policy.dtls_initial_timeout()), + .retransmission_timer = {}, + .flight_timer = {}, + })) { + BOTAN_ASSERT_NONNULL(m_token->callbacks); + } + + ~RetransmissionTimer() = default; + + RetransmissionTimer(const RetransmissionTimer&) = delete; + RetransmissionTimer& operator=(const RetransmissionTimer&) = delete; + RetransmissionTimer(RetransmissionTimer&&) = default; + RetransmissionTimer& operator=(RetransmissionTimer&&) = default; + + /// @returns true if the retransmission timer is currently armed; false otherwise + bool retransmissions_armed() const { return m_token->retransmission_timer.armed(); } + + /// @returns true if the flight timer is currently armed; false otherwise + bool flight_timeout_armed() const { return m_token->flight_timer.armed(); } + + /** + * @returns the time remaining until the next retransmission, the blanket + * flight timeout or std::nullopt if neither timer is armed. + * + * Note that this might return 0ms if the timer is armed and a deadline + * has been reached, but the deferred operation has not yet been executed. + */ + std::optional next_timeout() const { + if(!retransmissions_armed() && !flight_timeout_armed()) { + return std::nullopt; + } + + const auto next_retransmission = m_token->retransmission_timer.remaining(*m_token->callbacks); + const auto flight_timeout = m_token->flight_timer.remaining(*m_token->callbacks); + BOTAN_DEBUG_ASSERT(next_retransmission.has_value() || flight_timeout.has_value()); + + return std::min(next_retransmission.value_or(std::chrono::milliseconds::max()), + flight_timeout.value_or(std::chrono::milliseconds::max())); + } + + /** + * Stop any further time-based retransmissions. This is typically done + * when a flight has been acknowledged by the peer and no further + * retransmissions are needed. This does not affect the flight timer, + * which may be used to detect a flight timeout if no further progress + * is made after a flight was acknowledged. + */ + void stop_retransmissions() { reset_retransmission_timer(); } + + /** + * Disarm the timer and reset the retransmission counter. This is done + * when progress is made by receiving a full flight from the peer and the + * responsibility to produce a new flight now lies on us. In contrast to + * stop_retransmissions(), this also cancels the flight timer. + */ + void cancel() { + reset_retransmission_timer(); + m_token->flight_timer.cancel(); + } + + /** + * Arm (or restart) the timers when a *new* flight was just sent. + * Resets the timeout span to the initial value and the retransmission + * counter to zero. Optionally starts the blanket flight timer if it is + * configured. + * + * The operation @p on_retransmission will be executed consecutively + * with an exponential backoff until the configured maximum retransmission + * count is reached or the timer is cancelled. + * + * If the optional flight timeout is reached, retransmissions will be + * stopped as well. + */ + void start(DeferredOperation on_retransmission) { + reset_retransmission_timer(std::move(on_retransmission)); + set_retransmission_timer(m_token); + set_flight_timer(); + } + + /** + * Allows registering a callback that is invoked when the maximum + * retransmission count is reached or the blanket flight timeout expires. + * The callback is needed because the emitted exception from within the + * deferred operations cannot be caught by higher layers of the library's + * DTLS business logic as they typically are invoked by the application + * directly. + */ + void set_timeout_handler(TimeoutHandler handler) { m_token->on_timeout = std::move(handler); } + + private: + void set_flight_timer() { + if(auto timeout = m_token->flight_timeout) { + m_token->flight_timer = SingleshotTimer::start(m_token->callbacks, *timeout, on_flight_timeout(m_token)); + } + } + + void reset_retransmission_timer(DeferredOperation on_retransmission = {}) { + m_token->on_retransmission = std::move(on_retransmission); + m_token->retransmissions = 0; + m_token->next_timeout = m_token->initial_timeout; + m_token->retransmission_timer.cancel(); + } + + static void set_retransmission_timer(const std::shared_ptr& token) { + token->retransmission_timer = + SingleshotTimer::start(token->callbacks, token->next_timeout, on_retransmission_timeout(token)); + } + + static SingleshotTimer::DeferredOperation on_flight_timeout(const std::shared_ptr& token) { + return [weak = std::weak_ptr(token)] { + if(auto handle = weak.lock()) { + handle->retransmission_timer.cancel(); + if(handle->on_timeout) { + handle->on_timeout(); + } + throw TLS_Exception(Alert::None, + "DTLS (post-)handshake message exchange timed out: flight timeout exceeded"); + } + }; + } + + static SingleshotTimer::DeferredOperation on_retransmission_timeout(const std::shared_ptr& token) { + return [weak_token = std::weak_ptr(token)] { + if(auto handle = weak_token.lock()) { + if(handle->max_retransmissions.has_value() && + handle->retransmissions >= handle->max_retransmissions.value()) { + handle->flight_timer.cancel(); + if(handle->on_timeout) { + handle->on_timeout(); + } + throw TLS_Exception( + Alert::None, "DTLS (post-)handshake message exchange timed out: maximum retransmissions exceeded"); + } + + handle->on_retransmission(); + handle->next_timeout = std::min(2 * handle->next_timeout, handle->max_timeout); + handle->retransmissions++; + set_retransmission_timer(handle); + } + }; + } + + private: + std::shared_ptr m_token; +}; + +} // namespace Botan::TLS + +#endif diff --git a/src/lib/tls/dtls13/tls_types_dtls13.h b/src/lib/tls/dtls13/tls_types_dtls13.h new file mode 100644 index 00000000000..c0eaae92240 --- /dev/null +++ b/src/lib/tls/dtls13/tls_types_dtls13.h @@ -0,0 +1,25 @@ +/** + * DTLS 1.3 Strong Type Wrappers + * (C) 2026 Jack Lloyd + * 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity + * + * Botan is released under the Simplified BSD License (see license.txt) + */ + +#ifndef BOTAN_TLS_TYPES_DTLS13_H_ +#define BOTAN_TLS_TYPES_DTLS13_H_ + +#include + +#include +#include + +namespace Botan::TLS { + +using SequenceNumberHint = std::variant; + +using ConnectionID = Strong, struct ConnectionIDTag_>; + +} // namespace Botan::TLS + +#endif diff --git a/src/lib/tls/dtls13/tls_utils_dtls13.h b/src/lib/tls/dtls13/tls_utils_dtls13.h new file mode 100644 index 00000000000..5a0bb88cdb4 --- /dev/null +++ b/src/lib/tls/dtls13/tls_utils_dtls13.h @@ -0,0 +1,131 @@ +/* +* DTLS utilities +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#ifndef BOTAN_TLS_UTILS_DTLS_13_H_ +#define BOTAN_TLS_UTILS_DTLS_13_H_ + +#include + +namespace Botan::TLS { + +/** + * RFC 9147 4.2.2 + * [I]mplementations SHOULD reconstruct the sequence number by computing + * the full sequence number which is numerically closest to one plus the + * sequence number of the highest successfully deprotected record in the + * current epoch. + * + * The wire carries only the low 8 or 16 bits of the sequence number, so the + * full value is ambiguous modulo 2^bits (the "window"). We resolve the + * ambiguity by picking the value within the window that is closest to the + * expected next sequence number. This tolerates reordering and loss of up to + * half a window in either direction and ties at exactly half a window resolve + * to the higher value. + */ +constexpr uint64_t reconstruct_full_sequence_number(uint64_t highest_seen_seqno, SequenceNumberHint record_seqno_hint) { + return std::visit( + [&](T hint) { + constexpr size_t bits = sizeof(T) * 8; + constexpr uint64_t window = uint64_t{1} << bits; + constexpr uint64_t half_window = window / 2; + + const uint64_t expected = highest_seen_seqno + 1; + + // First guess: keep the high bits of the expected next sequence + // number and replace the low bits with the transmitted hint. This + // yields the unique value congruent to the hint modulo the window + // that differs from `expected` by less than a full window. + const uint64_t candidate = (expected & ~(window - 1)) | uint64_t(hint); + + // The first guess may still be up to a full window off. Shifting it + // by exactly one window preserves congruence with the hint, so pick + // whichever shift lands closest to `expected`. + if(candidate + half_window <= expected) { + return candidate + window; + } else if(candidate > expected + half_window && + candidate >= window /* prevent underflow at the start of an epoch */) { + return candidate - window; + } else { + return candidate; + } + }, + record_seqno_hint); +} + +class Replay_Window_13 { + private: + using window_type = uint64_t; + + public: + constexpr static size_t window_size = sizeof(window_type) * 8; + + public: + /** + * Adds the given sequence number to the replay window. Note that the + * reconstructed sequence number of an already authenticated record + * must be provided. + * + * RFC 9147 Section 4.5.1 + * The window MUST NOT be updated due to a received record until that + * record has been deprotected successfully. + * + * @returns false if the sequence number has already been seen or falls + * outside the window, true otherwise. + */ + constexpr bool accept(uint64_t sequence_number) { + // RFC 9147 Section 4.5.1 + // If the received record [...] is to the right of the window, + // then the record is new. + if(sequence_number > highest_sequence_number) { + const uint64_t offset = sequence_number - highest_sequence_number; + if(offset >= window_size) { + window = 0; + } else { + window <<= offset; + } + + highest_sequence_number = sequence_number; + window |= 1; // set bit for new highest sequence number + return true; + } + + const uint64_t offset = highest_sequence_number - sequence_number; + + // RFC 9147 Section 4.5.1 + // Records that contain sequence numbers lower than the "left" edge + // of the window are rejected. + if(offset >= window_size) { + return false; // too old + } + + // RFC 9147 Section 4.5.1 + // Records falling within the window are checked against a list of + // received records within the window. + const bool is_duplicate = ((window >> offset) & 1) == 1; + + // RFC 9147 Section 4.5.1 + // Duplicates are rejected [...]. + if(is_duplicate) { + return false; + } + + // RFC 9147 Section 4.5.1 + // If the received record falls within the window and is new, + // [...] then the record is new. + window |= (static_cast(1) << offset); + return true; + } + + private: + uint64_t highest_sequence_number = 0; + uint64_t window = 0; +}; + +} // namespace Botan::TLS + +#endif diff --git a/src/lib/tls/msg_client_hello.cpp b/src/lib/tls/msg_client_hello.cpp index 492e51cd69b..6936c5f6e7e 100644 --- a/src/lib/tls/msg_client_hello.cpp +++ b/src/lib/tls/msg_client_hello.cpp @@ -134,9 +134,12 @@ Protocol_Version Client_Hello_Internal::version() const { // the highest version indicated therein. const bool is_dtls = m_legacy_version.is_datagram_protocol(); const auto protocol_version_13 = is_dtls ? Protocol_Version::DTLS_V13 : Protocol_Version::TLS_V13; + if(!extensions().has() || !extensions().get()->supports(protocol_version_13)) { - return is_dtls ? Protocol_Version::DTLS_V12 : Protocol_Version::TLS_V12; + // The exact legacy_version is ignored we just inspect it to + // distinguish TLS and DTLS. + return m_legacy_version.flavor().legacy_version(); } // Note: The Client_Hello_13 class will make sure that legacy_version diff --git a/src/lib/tls/tls13/tls_channel_impl_13.cpp b/src/lib/tls/tls13/tls_channel_impl_13.cpp index 15582c50de0..3cc5a0d2324 100644 --- a/src/lib/tls/tls13/tls_channel_impl_13.cpp +++ b/src/lib/tls/tls13/tls_channel_impl_13.cpp @@ -65,6 +65,10 @@ Channel_Impl_13::Channel_Impl_13(const std::shared_ptr& callbacks, BOTAN_ASSERT_NONNULL(m_policy); } +void Channel_Impl_13::init() { + m_channel_io->init(std::dynamic_pointer_cast(shared_from_this())); +} + Cipher_State& Channel_Impl_13::setup_cipher_state(std::unique_ptr cipher_state) { BOTAN_ASSERT_NONNULL(cipher_state); m_cipher_state = std::move(cipher_state); @@ -247,6 +251,9 @@ bool Channel_Impl_13::timeout_check() { return false; } + // timeout_check() is deprecated and will be removed with Botan4. Users of + // DTLS 1.2 that now enabled DTLS 1.3 will need to migrate their code to use + // TLS::Callbacks::tls_register_deferred_operation() before Botan4. throw Not_Implemented( "timeout_check() is not implemented for DTLS 1.3, please implement " "TLS::Callbacks::tls_register_deferred_operation() instead"); @@ -345,7 +352,15 @@ void Channel_Impl_13::process(const Alert_Record& alert_record) { const bool is_fatal_error_alert = is_error_alert(alert) && alert.is_fatal(); if(!is_close_notify_alert(alert) && !is_fatal_error_alert) { - note_useless_record(policy()); + // RFC 9147 Section 4.5.2 + // In general, invalid records SHOULD be silently discarded [...]. + // + // Plaintext (epoch 0) records are unauthenticated. They neither trip nor + // reset the limit of useless records, so that an off-path attacker + // cannot tear down an association with forged warning alerts. + if(!alert_record.epoch.has_value() || alert_record.epoch->is_protected()) { + note_useless_record(policy()); + } } if(is_fatal_error_alert) { @@ -361,9 +376,21 @@ void Channel_Impl_13::process(const Alert_Record& alert_record) { } void Channel_Impl_13::process(const ChangeCipherSpec_Record& ccs_record) { - BOTAN_UNUSED(ccs_record); + // A more graceful check was already performed in the Record_Layer. + BOTAN_ASSERT_IMPLICATION(ccs_record.epoch.has_value(), + ccs_record.epoch->is_unprotected(), + "CCS records are always unprotected in DTLS 1.3"); + process_dummy_change_cipher_spec(); - note_useless_record(policy()); + + // In TLS 1.3, a dummy CCS record is a "compatibility" artefact and does not + // carry any further value, thereby counting towards the useless record + // limit. In DTLS 1.3, it may only occur during a downgrade to DTLS 1.2, but + // unprotected records in DTLS don't count towards this limit in the first + // place because they may come from an off-path attacker. + if(m_flavor.is_streaming()) { + note_useless_record(policy()); + } } void Channel_Impl_13::process(const ApplicationData_Record& record) { diff --git a/src/lib/tls/tls13/tls_channel_impl_13.h b/src/lib/tls/tls13/tls_channel_impl_13.h index be7c19b63a2..1db578bf443 100644 --- a/src/lib/tls/tls13/tls_channel_impl_13.h +++ b/src/lib/tls/tls13/tls_channel_impl_13.h @@ -100,6 +100,12 @@ class Channel_Impl_13 : public Channel_Impl { throw Invalid_Argument("renegotiation is not allowed in TLS 1.3"); } + /** + * Terminate the connection (on sending or receiving an error alert) and + * clear secrets + */ + void shutdown(); + /** * Attempt to update the session's traffic key material * Note that this is possible with a TLS 1.3 channel, only. @@ -143,6 +149,8 @@ class Channel_Impl_13 : public Channel_Impl { Cipher_State* cipher_state() { return m_cipher_state.get(); } protected: + void init(); + Cipher_State& setup_cipher_state(std::unique_ptr cipher_state); virtual void process_handshake_msg(Handshake_Message_13 msg) = 0; @@ -177,12 +185,6 @@ class Channel_Impl_13 : public Channel_Impl { void process(const ChangeCipherSpec_Record& ccs_record); void process(const ApplicationData_Record& app_data_record); - /** - * Terminate the connection (on sending or receiving an error alert) and - * clear secrets - */ - void shutdown(); - protected: #if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT) /** diff --git a/src/lib/tls/tls13/tls_channel_io.cpp b/src/lib/tls/tls13/tls_channel_io.cpp index d61a565f582..18c448700f8 100644 --- a/src/lib/tls/tls13/tls_channel_io.cpp +++ b/src/lib/tls/tls13/tls_channel_io.cpp @@ -21,6 +21,10 @@ #include #include +#if defined(BOTAN_HAS_DTLS_13) + #include +#endif + namespace Botan::TLS { std::optional Channel_IO::next_pending_handshake_message( @@ -101,6 +105,10 @@ Channel_IO::ReceiveEvent Channel_IO::next_pending_event(std::optional std::optional { + process(record); + return std::nullopt; // continue looping, the record layer may have more data... + }, [&](TransparentRecord anything_else) -> std::optional { validate(anything_else); return generalize_to(std::move(anything_else)); @@ -157,6 +165,25 @@ void Channel_IO::maybe_send_opportunistic_key_update() { return write_limit > 0 && cs->current_read_sequence_number() >= read_limit; }; + // RFC 9147 4.7.3 + // Implementations SHOULD initiate a key update with update_requested + // before reaching [the deprotection failure limit]. + const auto deprotection_failure_limit_reached = [&] { + if(m_flavor.is_streaming()) { + return false; + } + + // This only makes sense if the limit set by the user is >= 2. + const size_t failure_limit = policy().dtls_maximum_deprotection_failures(); + if(failure_limit < 2) { + return false; + } + + // Ask for the update a quarter before the limit, but at least one failure ahead of it. + const uint64_t threshold = failure_limit - std::max(1, failure_limit / 4); + return cs->current_read_epoch_deprotection_failures() >= threshold; + }; + // RFC 9846 4.7.3 // If the request_update field [of a received KeyUpdate] is set to // "update_requested", then the receiver MUST send a KeyUpdate of its own @@ -179,7 +206,8 @@ void Channel_IO::maybe_send_opportunistic_key_update() { // write keys, provided that we are allowed to request one. const bool request_peer_update = may_request_peer_update && // (write_limit_reached || // - read_limit_reached()); + read_limit_reached() || // + deprotection_failure_limit_reached()); if(m_key_update_reciprocation_pending || write_limit_reached || request_peer_update) { update_traffic_keys(request_peer_update); @@ -328,7 +356,9 @@ constexpr size_t max_retained_write_buffer_size = 4 * (TLS_HEADER_SIZE + MAX_CIP class TLS_Channel_IO final : public Channel_IO { public: TLS_Channel_IO(Connection_Side side, std::shared_ptr policy, std::shared_ptr callbacks) : - Channel_IO(side, std::move(policy), std::move(callbacks)), m_record_layer(side), m_handshake_layer(side) {} + Channel_IO(side, TLS_Flavor::TLS, std::move(policy), std::move(callbacks)), + m_record_layer(side), + m_handshake_layer(side) {} void send_data(Record_Type record_type, std::span payload, Cipher_State* cipher_state) override { const size_t max_plaintext_payload_size = record_layer().record_payload_size_limit(policy(), cipher_state); @@ -459,6 +489,11 @@ class TLS_Channel_IO final : public Channel_IO { std::ignore = m_handshake_layer.copy_data(policy(), record); } + void process(const ACK_Record& ack_record) override { + BOTAN_UNUSED(ack_record); + throw Unexpected_Message("Received ACK record in TLS 1.3"); + } + void validate(const TransparentRecord& record) override { BOTAN_UNUSED(record); @@ -510,7 +545,11 @@ std::shared_ptr Channel_IO::create(Connection_Side side, std::shared_ptr policy, std::shared_ptr callbacks) { if(flavor.is_datagram()) { - throw Not_Implemented("DTLS 1.3 is not yet supported"); +#if defined(BOTAN_HAS_DTLS_13) + return std::make_shared(side, std::move(policy), std::move(callbacks)); +#else + throw Not_Implemented("DTLS 1.3 is not enabled in this build of Botan"); +#endif } else { return std::make_shared(side, std::move(policy), std::move(callbacks)); } diff --git a/src/lib/tls/tls13/tls_channel_io.h b/src/lib/tls/tls13/tls_channel_io.h index cdb64f1a9eb..999bbf27df3 100644 --- a/src/lib/tls/tls13/tls_channel_io.h +++ b/src/lib/tls/tls13/tls_channel_io.h @@ -21,6 +21,7 @@ class Alert; class Record_Layer; class Handshake_Layer; class Cipher_State; +class Channel_Impl_13; struct RecordNumber; /** @@ -51,8 +52,11 @@ class BOTAN_TEST_API Channel_IO { std::shared_ptr callbacks); protected: - Channel_IO(Connection_Side side, std::shared_ptr policy, std::shared_ptr callbacks) : - m_policy(std::move(policy)), m_callbacks(std::move(callbacks)), m_side(side) {} + Channel_IO(Connection_Side side, + TLS_Flavor flavor, + std::shared_ptr policy, + std::shared_ptr callbacks) : + m_policy(std::move(policy)), m_callbacks(std::move(callbacks)), m_side(side), m_flavor(flavor) {} public: Channel_IO(const Channel_IO&) = delete; @@ -179,9 +183,10 @@ class BOTAN_TEST_API Channel_IO { * DTLS only: if a flight is not acknowledged within the timeout, it must * be retransmitted. If no timeout is armed, this returns std::nullopt. * - * Note that this also reports the timeout for the next ACK timer, if any. - * However, it does not report internal housekeeping timers (e.g. for - * deferred epoch pruning). + * Note that this also reports the timeout for the next ACK timer, if any, + * as well as the deadline of the blanket flight timeout, which may remain + * armed after retransmissions have stopped. It does not report internal + * housekeeping timers (e.g. for deferred epoch pruning). */ virtual std::optional next_retransmission_timeout() const = 0; @@ -211,6 +216,8 @@ class BOTAN_TEST_API Channel_IO { notify_closed_for_writing(); } + virtual void init(const std::shared_ptr& channel) { BOTAN_UNUSED(channel); } + void set_cipher_state(std::weak_ptr cipher_state) { m_cipher_state = std::move(cipher_state); } void set_record_size_limits(uint16_t out, uint16_t in); @@ -224,6 +231,7 @@ class BOTAN_TEST_API Channel_IO { void send_dummy_change_cipher_spec(); virtual void process(const Handshake_Record& record) = 0; + virtual void process(const ACK_Record& ack_record) = 0; virtual void validate(const TransparentRecord& record) = 0; virtual void send_data(Record_Type record_type, std::span payload, Cipher_State* cipher_state) = 0; @@ -237,7 +245,8 @@ class BOTAN_TEST_API Channel_IO { virtual void send_flight(std::vector flight, Expected_Response expected) = 0; /// Marshalls and sends the given KeyUpdate message, then advances the - /// write epoch. + /// write epoch. Note that DTLS 1.3 defers advancing the write epoch + /// until the KeyUpdate is acknowledged (RFC 9147 8). virtual void send_key_update(const Key_Update& msg) = 0; virtual Record_Layer& record_layer() = 0; @@ -255,6 +264,8 @@ class BOTAN_TEST_API Channel_IO { Callbacks& callbacks() const { return *m_callbacks; } + std::shared_ptr shared_callbacks() const { return m_callbacks; } + private: void maybe_send_opportunistic_key_update(); @@ -292,6 +303,7 @@ class BOTAN_TEST_API Channel_IO { std::shared_ptr m_policy; std::shared_ptr m_callbacks; Connection_Side m_side; + TLS_Flavor m_flavor; }; } // namespace Botan::TLS diff --git a/src/lib/tls/tls13/tls_cipher_state.cpp b/src/lib/tls/tls13/tls_cipher_state.cpp index 301c7881970..0454e73aec5 100644 --- a/src/lib/tls/tls13/tls_cipher_state.cpp +++ b/src/lib/tls/tls13/tls_cipher_state.cpp @@ -112,11 +112,19 @@ #include #include +#if defined(BOTAN_HAS_DTLS_13) + #include +#endif + namespace Botan::TLS { std::unique_ptr Cipher_State::create(Connection_Side side, TLS_Flavor flavor, std::string_view prf_algo) { if(flavor.is_datagram()) { - throw Not_Implemented("DTLS 1.3 is not yet supported"); +#if defined(BOTAN_HAS_DTLS_13) + return std::make_unique(side, prf_algo); +#else + throw Not_Implemented("DTLS 1.3 is not enabled in this build of Botan"); +#endif } else { return std::make_unique(side, prf_algo); } @@ -466,11 +474,7 @@ std::array current_nonce(const uint64_t seq_no, std::span size_t Cipher_State::protected_record_length(Epoch& epoch, size_t payload_length, size_t padding_bytes) { BOTAN_ASSERT_NONNULL(epoch.cipher); - // RFC 8446 5.2 - // type: The TLSPlaintext.type value containing the content type of the record. - constexpr size_t content_type_tag_length = 1; - - const size_t plaintext_length = payload_length + content_type_tag_length + padding_bytes; + const size_t plaintext_length = payload_length + CONTENT_TYPE_TAG_LENGTH + padding_bytes; return epoch.cipher->output_length(plaintext_length); } @@ -688,6 +692,7 @@ Cipher_State::Epoch Cipher_State::create_epoch(EpochNumber epoch_number, }(), .iv = hkdf_expand_label(traffic_secret, "iv", {}, NONCE_LENGTH), .sequence_number = 0, + .deprotection_failures = 0, .traffic_secret = traffic_secret, .finished_key = [&]() -> std::optional> { if(epoch_number.is_handshake_traffic()) { @@ -797,6 +802,10 @@ uint64_t Cipher_State::current_read_sequence_number() const { return latest_read_epoch().sequence_number; } +uint64_t Cipher_State::current_read_epoch_deprotection_failures() const { + return latest_read_epoch().deprotection_failures; +} + EpochNumber Cipher_State::current_write_epoch_number() const { return has_write_epoch() ? latest_write_epoch().number : EpochNumber::unprotected(); } diff --git a/src/lib/tls/tls13/tls_cipher_state.h b/src/lib/tls/tls13/tls_cipher_state.h index 51dd2a6b72f..cf5ef940b65 100644 --- a/src/lib/tls/tls13/tls_cipher_state.h +++ b/src/lib/tls/tls13/tls_cipher_state.h @@ -88,6 +88,7 @@ class BOTAN_TEST_API Cipher_State { std::unique_ptr cipher; secure_vector iv; uint64_t sequence_number; + uint64_t deprotection_failures; secure_vector traffic_secret; @@ -314,6 +315,15 @@ class BOTAN_TEST_API Cipher_State { */ uint64_t current_read_sequence_number() const; + /** + * In DTLS deprotection failures of received records is not a fatal error + * and the counter is needed to determine when a KeyUpdate is required. + * For TLS, this will always return 0. + * + * @returns the number of failed deprotections in the current read epoch. + */ + uint64_t current_read_epoch_deprotection_failures() const; + /** * Register an optional callback function to extract secrets bound for a * SSLKEYLOGFILE. See SSLKEYLOGFILE RFC 9850 for details. diff --git a/src/lib/tls/tls13/tls_client_impl_13.cpp b/src/lib/tls/tls13/tls_client_impl_13.cpp index 149d3382332..5ce83428545 100644 --- a/src/lib/tls/tls13/tls_client_impl_13.cpp +++ b/src/lib/tls/tls13/tls_client_impl_13.cpp @@ -34,6 +34,7 @@ std::shared_ptr Client_Impl_13::create(const std::shared_ptr& next_protocols) { auto self = std::make_shared( Private{}, callbacks, session_manager, creds, policy, rng, flavor, std::move(server_info)); + self->init(); #if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT) if(self->is_datagram() ? policy->allow_dtls12() : policy->allow_tls12()) { @@ -41,13 +42,6 @@ std::shared_ptr Client_Impl_13::create(const std::shared_ptrexpects_downgrade()) { - // If we don't expect to downgrade, we can already enable all DTLS-only - // features (e.g. record ACKing), because we know that we won't ever - // talk to a legacy peer and succeed a handshake. - self->m_channel_io->notify_protocol_version_committed(); - } - if(auto session = self->find_session_for_resumption()) { if(session->session.version().is_tls_13_or_later()) { self->m_handshake->resumed_session = std::move(session); @@ -272,6 +266,32 @@ void Client_Impl_13::handle(const Server_Hello_12_Shim& server_hello_msg) { #endif } +void Client_Impl_13::handle(const Hello_Verify_Request_Shim& /*hello_verify_request*/) { + BOTAN_ASSERT_NONNULL(m_handshake); + + // HelloVerifyRequest exists only in DTLS. A TLS peer must never reach this + // handler because HelloVerifyRequest is not among the TLS expected messages. + BOTAN_STATE_CHECK(is_datagram()); + + if(!expects_downgrade()) { + throw TLS_Exception(Alert::ProtocolVersion, "Received an unexpected Hello Verify Request"); + } + + if(m_handshake->state.has_hello_retry_request()) { + throw TLS_Exception(Alert::UnexpectedMessage, "Hello Verify Request received after Hello Retry"); + } + +#if defined(BOTAN_HAS_TLS_DOWNGRADE_SUPPORT) + preserve_client_hello(m_handshake->state.take_client_hello()); + preserve_sequence_numbers(m_channel_io->epoch0_sequence_numbers()); + request_downgrade(); + + // After this, no further messages are expected here because this instance will be replaced + // by a Client_Impl_12. + m_handshake->transitions.set_expected_next({}); +#endif +} + namespace { // validate Server_Hello_13 and Hello_Retry_Request void validate_server_hello_ish(const Client_Hello_13& ch, const Server_Hello_13& sh, TLS_Flavor flavor) { @@ -361,6 +381,13 @@ void Client_Impl_13::handle(const Server_Hello_13& sh) { } else { // We just received a TLS 1.3 ServerHello without ever receiving a // HelloRetryRequest. Now, we can be sure that our peer uses TLS 1.3. + // + // Conceptually, DTLS could now clear the resend buffer and rely on the + // ACKing of DTLS 1.3 in case the encrypted portion of the server flight + // was lost. However, we don't do that here for compliance with BoGo, + // i.e., we keep the resend buffer and the next timeout_check() call will + // trigger a full resend of all ClientHello fragments, which is still + // valid behavior. m_channel_io->notify_protocol_version_committed(); } diff --git a/src/lib/tls/tls13/tls_client_impl_13.h b/src/lib/tls/tls13/tls_client_impl_13.h index e55a03a8e3f..815ccadc516 100644 --- a/src/lib/tls/tls13/tls_client_impl_13.h +++ b/src/lib/tls/tls13/tls_client_impl_13.h @@ -104,6 +104,7 @@ class Client_Impl_13 final : public Channel_Impl_13 { using Channel_Impl_13::handle; void handle(const Server_Hello_12_Shim& server_hello_msg); + void handle(const Hello_Verify_Request_Shim& hello_verify_request); void handle(const Server_Hello_13& server_hello_msg); void handle(const Hello_Retry_Request& hrr_msg); void handle(const Encrypted_Extensions& encrypted_extensions_msg); diff --git a/src/lib/tls/tls13/tls_handshake_layer_13.cpp b/src/lib/tls/tls13/tls_handshake_layer_13.cpp index b1515460e67..3244b1a8132 100644 --- a/src/lib/tls/tls13/tls_handshake_layer_13.cpp +++ b/src/lib/tls/tls13/tls_handshake_layer_13.cpp @@ -273,8 +273,8 @@ std::optional Handshake_Layer::next_message(const Policy& // messages can immediately precede a key change, implementations // MUST send these messages in alignment with a record boundary. // - // Note: Hello_Retry_Request and Hello_Verify_Request were added to the list - // below although they cannot immediately precede a key change. + // Note: Hello_Retry_Request and Hello_Verify_Request_Shim were added to the + // list below although they cannot immediately precede a key change. // However, there cannot be any further sensible messages in the record // after them. // @@ -289,7 +289,12 @@ std::optional Handshake_Layer::next_message(const Policy& // available handshake messages. (Any legal follow-up handshake message // cannot be present in the queue yet, because we can successfully deprotect // it only after said key change.) - if(holds_any_of(msg) && + if(holds_any_of 1.2 downgrade + Hello_Retry_Request, + Finished_13>(msg) && has_pending_data()) { throw TLS_Exception(Alert::UnexpectedMessage, "Unexpected additional handshake data at epoch boundary"); } diff --git a/src/lib/tls/tls13/tls_handshake_state_13.cpp b/src/lib/tls/tls13/tls_handshake_state_13.cpp index a38c37399d0..62a71390672 100644 --- a/src/lib/tls/tls13/tls_handshake_state_13.cpp +++ b/src/lib/tls/tls13/tls_handshake_state_13.cpp @@ -50,6 +50,13 @@ Hello_Retry_Request& Handshake_State_13_Base::store(Hello_Retry_Request hello_re return m_hello_retry_request.value(); } +Hello_Verify_Request_Shim& Handshake_State_13_Base::store(Hello_Verify_Request_Shim hello_verify_request, + const bool /*from_peer*/) { + BOTAN_STATE_CHECK(!m_hello_verify_request_12.has_value()); + m_hello_verify_request_12 = std::move(hello_verify_request); + return m_hello_verify_request_12.value(); +} + Encrypted_Extensions& Handshake_State_13_Base::store(Encrypted_Extensions encrypted_extensions, const bool /*from_peer*/) { BOTAN_STATE_CHECK(!m_encrypted_extensions.has_value()); diff --git a/src/lib/tls/tls13/tls_handshake_state_13.h b/src/lib/tls/tls13/tls_handshake_state_13.h index 314bd0b5817..0ce29d608d7 100644 --- a/src/lib/tls/tls13/tls_handshake_state_13.h +++ b/src/lib/tls/tls13/tls_handshake_state_13.h @@ -94,6 +94,7 @@ class BOTAN_TEST_API Handshake_State_13_Base { Server_Hello_13& store(Server_Hello_13 server_hello, bool from_peer); Server_Hello_12_Shim& store(Server_Hello_12_Shim server_hello, bool from_peer); Hello_Retry_Request& store(Hello_Retry_Request hello_retry_request, bool from_peer); + Hello_Verify_Request_Shim& store(Hello_Verify_Request_Shim hello_verify_request, bool from_peer); Encrypted_Extensions& store(Encrypted_Extensions encrypted_extensions, bool from_peer); Certificate_Request_13& store(Certificate_Request_13 certificate_request, bool from_peer); Certificate_13& store(Certificate_13 certificate, bool from_peer); @@ -125,6 +126,7 @@ class BOTAN_TEST_API Handshake_State_13_Base { std::optional m_server_hello; std::optional m_server_hello_12; std::optional m_hello_retry_request; + std::optional m_hello_verify_request_12; std::optional m_encrypted_extensions; std::optional m_certificate_request; std::optional m_server_certificate; diff --git a/src/lib/tls/tls13/tls_messages_13.h b/src/lib/tls/tls13/tls_messages_13.h index 7fef6351863..3c45226746e 100644 --- a/src/lib/tls/tls13/tls_messages_13.h +++ b/src/lib/tls/tls13/tls_messages_13.h @@ -472,6 +472,7 @@ using Handshake_Message_13 = std::variant; using Client_Post_Handshake_13_Message = std::variant; -using Server_Handshake_13_Message = std::variant; +using Server_Handshake_13_Message = + std::variant; using Server_Handshake_13_Message_Ref = detail::as_wrapped_references_t; using Client_Handshake_13_Message = diff --git a/src/lib/tls/tls13/tls_record_13.cpp b/src/lib/tls/tls13/tls_record_13.cpp index 9f6c2d5b8ab..3b881792e8c 100644 --- a/src/lib/tls/tls13/tls_record_13.cpp +++ b/src/lib/tls/tls13/tls_record_13.cpp @@ -28,6 +28,9 @@ Record annotate_record_type(Record_Content&& record) { case Record_Type::ApplicationData: return ApplicationData_Record{std::move(record)}; + case Record_Type::ACK: + return ACK_Record{std::move(record)}; + case Record_Type::Invalid: case Record_Type::Heartbeat: // not supported break; diff --git a/src/lib/tls/tls13/tls_record_13.h b/src/lib/tls/tls13/tls_record_13.h index c1a9e7bbed7..a98c37030ec 100644 --- a/src/lib/tls/tls13/tls_record_13.h +++ b/src/lib/tls/tls13/tls_record_13.h @@ -39,7 +39,10 @@ struct Handshake_Record final : public Record_Content {}; struct ApplicationData_Record final : public Record_Content {}; -using Record = std::variant; +struct ACK_Record final : public Record_Content {}; + +using Record = + std::variant; /** * Takes a generic @p record and transforms it into one of the strong typed diff --git a/src/lib/tls/tls13/tls_record_layer_13.cpp b/src/lib/tls/tls13/tls_record_layer_13.cpp index 8609001324e..ca6701f0125 100644 --- a/src/lib/tls/tls13/tls_record_layer_13.cpp +++ b/src/lib/tls/tls13/tls_record_layer_13.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include #include @@ -23,10 +24,6 @@ namespace Botan::TLS { namespace { -// RFC 9846 5.2 -// type: The TLSPlaintext.type value containing the content type of the record. -constexpr uint16_t content_type_tag_length = 1; - bool verify_change_cipher_spec(std::span data) { // RFC 8446 5. // An implementation may receive an unencrypted record of type @@ -42,8 +39,8 @@ bool verify_change_cipher_spec(std::span data) { } // namespace Record_Layer::Record_Layer() : - m_outgoing_record_size_limit(MAX_PLAINTEXT_SIZE + content_type_tag_length), - m_incoming_record_size_limit(MAX_PLAINTEXT_SIZE + content_type_tag_length), + m_outgoing_record_size_limit(MAX_PLAINTEXT_SIZE + CONTENT_TYPE_TAG_LENGTH), + m_incoming_record_size_limit(MAX_PLAINTEXT_SIZE + CONTENT_TYPE_TAG_LENGTH), // RFC 8446 5.1 // legacy_record_version: MUST be set to 0x0303 for all records @@ -70,7 +67,7 @@ void Record_Layer::set_record_size_limits(const uint16_t outgoing_limit, const u // Endpoints MUST NOT send a "record_size_limit" extension with a value // smaller than 64. BOTAN_ARG_CHECK(outgoing_limit >= 64, "Invalid outgoing record size limit"); - BOTAN_ARG_CHECK(incoming_limit >= 64 && incoming_limit <= MAX_PLAINTEXT_SIZE + content_type_tag_length, + BOTAN_ARG_CHECK(incoming_limit >= 64 && incoming_limit <= MAX_PLAINTEXT_SIZE + CONTENT_TYPE_TAG_LENGTH, "Invalid incoming record size limit"); // RFC 8449 4. @@ -78,7 +75,7 @@ void Record_Layer::set_record_size_limits(const uint16_t outgoing_limit, const u // MUST NOT send records larger than the protocol-defined limit, unless // explicitly allowed by a future TLS version or extension. m_outgoing_record_size_limit = - std::min(outgoing_limit, static_cast(MAX_PLAINTEXT_SIZE + content_type_tag_length)); + std::min(outgoing_limit, static_cast(MAX_PLAINTEXT_SIZE + CONTENT_TYPE_TAG_LENGTH)); m_incoming_record_size_limit = incoming_limit; } @@ -158,7 +155,7 @@ RecordNumber TLS_Record_Layer::prepare_record(Record_Type type, "Zero-length fragments are only allowed for Application Data"); if(cs != nullptr) { - const size_t pt_size_with_type_tag = payload.size() + content_type_tag_length; + const size_t pt_size_with_type_tag = payload.size() + CONTENT_TYPE_TAG_LENGTH; const size_t max_record_size = outgoing_record_size_limit(); // Don't even bother consulting the policy if we already filled the @@ -222,7 +219,7 @@ uint16_t TLS_Record_Layer::record_payload_size_limit(const Policy& policy, // Hence, this calculates the maximum amount of actual application data // payload bytes that can be transferred in a single record (assuming no // further padding is applied by the policy). - return (cipher_state != nullptr) ? outgoing_record_size_limit() - content_type_tag_length + return (cipher_state != nullptr) ? outgoing_record_size_limit() - CONTENT_TYPE_TAG_LENGTH : static_cast(MAX_PLAINTEXT_SIZE); } diff --git a/src/lib/tls/tls13/tls_server_impl_13.cpp b/src/lib/tls/tls13/tls_server_impl_13.cpp index 84a71ef0293..de1368d6c36 100644 --- a/src/lib/tls/tls13/tls_server_impl_13.cpp +++ b/src/lib/tls/tls13/tls_server_impl_13.cpp @@ -30,6 +30,7 @@ std::shared_ptr Server_Impl_13::create(const std::shared_ptr(Private{}, callbacks, session_manager, credentials_manager, policy, rng, flavor); + self->init(); #if defined(BOTAN_HAS_TLS_12) if(flavor.is_streaming() ? policy->allow_tls12() : policy->allow_dtls12()) { diff --git a/src/lib/tls/tls13/tls_types_13.h b/src/lib/tls/tls13/tls_types_13.h index 97dc229ac3c..267d495be3e 100644 --- a/src/lib/tls/tls13/tls_types_13.h +++ b/src/lib/tls/tls13/tls_types_13.h @@ -10,6 +10,7 @@ #define BOTAN_TLS_TYPES_13_H_ #include +#include #include #include #include @@ -115,6 +116,18 @@ using MarshalledHandshakeMessage = Strong, struct Marshalle /// multiple handshake messages along with their handshake protocol headers. using MarshalledHandshakeMessageFlight = Strong, struct MarshalledHandshakeMessageFlight_>; +/// Holds the serialization of a single TLS 1.3 handshake message fragment along +/// with the handshake protocol header. This is used in DTLS' fragmentation. +using MarshalledHandshakeMessageFragment = Strong, struct MarshalledHandshakeMessageFragment_>; + +/// Holds a bunch of marshalled handshake message fragments that are packed into +/// a single record payload. This is used in DTLS' fragmentation. +using PackedHandshakeMessageFragments = Strong, struct PackedHandshakeMessageFragments_>; + +/// Holds the serialization of a single TLS 1.3 record along with the record +/// protocol header. Protected records hold the encrypted payload and AEAD tag. +using MarshalledRecord = Strong, struct MarshalledRecord_>; + /** * Wraps the epoch0 (unprotected) sequence numbers that are being handed down * from a DTLS 1.3 handshake to a DTLS 1.2 handshake during protocol downgrade. diff --git a/src/lib/tls/tls_channel.h b/src/lib/tls/tls_channel.h index 2cb99c535d8..2a840ef9b5b 100644 --- a/src/lib/tls/tls_channel.h +++ b/src/lib/tls/tls_channel.h @@ -124,17 +124,19 @@ class BOTAN_PUBLIC_API(2, 0) Channel { /** * This accessor determines whether a DTLS association currently has some - * retransmission pending and if so, how long until the next retransmission - * is scheduled. + * timer armed (retransmissions, an ACK timer, or - for DTLS 1.3 - the + * blanket flight timeout) and if so, how long until the earliest of them + * is scheduled to expire. * * If you're still using the deprecated timeout_check() function and this * returns a non-empty value, you should call timeout_check() after the - * specified duration has elapsed. If you are already using the new - * TLS::Callbacks::tls_register_deferred_operation() mechanism, this - * function still reports the correct times but is purely informational. + * specified duration has elapsed. Note that this works for DTLS 1.2 only; + * DTLS 1.3 requires the TLS::Callbacks::tls_register_deferred_operation() + * mechanism. If you are already using it, this function still reports the + * correct times but is purely informational. * - * @return the remaining time until the next retransmission or std::nullopt - * if no retransmission is currently scheduled + * @return the remaining time until the next timer expiry or std::nullopt + * if no timer is currently armed */ virtual std::optional next_retransmission_timeout() const = 0; diff --git a/src/lib/tls/tls_channel_impl.h b/src/lib/tls/tls_channel_impl.h index fa137fc75e2..2dc6a784948 100644 --- a/src/lib/tls/tls_channel_impl.h +++ b/src/lib/tls/tls_channel_impl.h @@ -35,6 +35,7 @@ namespace TLS { class Client; class Server; +class DTLS_Channel_IO; class Channel_Impl : public std::enable_shared_from_this { protected: @@ -313,6 +314,8 @@ class Channel_Impl : public std::enable_shared_from_this { #endif + friend class DTLS_Channel_IO; + /** * Indicates whether a downgrade to TLS 1.2 or lower is in progress * diff --git a/src/lib/tls/tls_client.cpp b/src/lib/tls/tls_client.cpp index 3fa97604a63..365369da1ec 100644 --- a/src/lib/tls/tls_client.cpp +++ b/src/lib/tls/tls_client.cpp @@ -46,11 +46,6 @@ Client::Client(const std::shared_ptr& callbacks, if(offer_version.is_tls_13_or_later()) { const auto flavor = offer_version.flavor(); - if(flavor.is_datagram()) { - // DTLS 1.3 is not yet supported. - throw Not_Implemented("DTLS 1.3 is not yet supported"); - } - m_impl = Client_Impl_13::create( callbacks, session_manager, creds, policy, rng, flavor, std::move(info), next_protocols); diff --git a/src/lib/tls/tls_extensions.cpp b/src/lib/tls/tls_extensions.cpp index 77479ec4c96..e5526a97021 100644 --- a/src/lib/tls/tls_extensions.cpp +++ b/src/lib/tls/tls_extensions.cpp @@ -925,6 +925,14 @@ Supported_Versions::Supported_Versions(Protocol_Version offer, const Policy& pol m_versions.push_back(Protocol_Version::TLS_V13); } } + #if defined(BOTAN_HAS_DTLS_13) + else { + if(offer >= Protocol_Version::DTLS_V13 && policy.allow_dtls13()) { + m_versions.push_back(Protocol_Version::DTLS_V13); + } + } + #endif + #endif #if defined(BOTAN_HAS_TLS_12) diff --git a/src/lib/tls/tls_magic.h b/src/lib/tls/tls_magic.h index bea6b4cfd47..17ff8c78b07 100644 --- a/src/lib/tls/tls_magic.h +++ b/src/lib/tls/tls_magic.h @@ -64,6 +64,8 @@ enum class Record_Type : uint8_t { ApplicationData = 23, Heartbeat = 24, // RFC 6520 + + ACK = 26, // RFC 9147 (DTLS 1.3) }; enum class Handshake_Type : uint8_t { @@ -124,6 +126,18 @@ constexpr uint64_t DOWNGRADE_TLS11 = 0x444F574E47524400; */ constexpr uint64_t DOWNGRADE_TLS12 = 0x444F574E47524401; +/** + * BoringSSL reports a sub-15ms remainder as zero (ssl/d1_lib.cc + * DTLSTimer::MicrosecondsRemaining) to absorb divergence with caller + * scheduling; BoGo's DTLS-Retransmit-Fudge test requires it. The cap keeps the + * fudge from swallowing the very short timers some tests configure. + */ +constexpr uint64_t DTLS_RETRANSMISSION_TIMER_FUDGE = 15; + +// RFC 9846 5.2 +// type: The TLSPlaintext.type value containing the content type of the record. +constexpr size_t CONTENT_TYPE_TAG_LENGTH = 1; + } // namespace Botan::TLS #endif diff --git a/src/lib/tls/tls_policy.cpp b/src/lib/tls/tls_policy.cpp index 6ef44478cc9..461af0673e3 100644 --- a/src/lib/tls/tls_policy.cpp +++ b/src/lib/tls/tls_policy.cpp @@ -15,8 +15,11 @@ #include #include #include +#include #include #include +#include +#include #include #include @@ -317,6 +320,12 @@ bool Policy::acceptable_protocol_version(Protocol_Version version) const { } #endif +#if defined(BOTAN_HAS_DTLS_13) + if(version == Protocol_Version::DTLS_V13 && allow_dtls13()) { + return true; + } +#endif + #if defined(BOTAN_HAS_TLS_12) if(version == Protocol_Version::TLS_V12 && allow_tls12()) { return true; @@ -393,7 +402,11 @@ bool Policy::allow_dtls12() const { } bool Policy::allow_dtls13() const { - return false; // DTLS 1.3 is not yet supported +#if defined(BOTAN_HAS_DTLS_13) + return true; +#else + return false; +#endif } bool Policy::include_time_in_hello_random() const { @@ -524,6 +537,74 @@ size_t Policy::dtls_maximum_timeout() const { return 60 * 1000; } +std::optional Policy::dtls_flight_timeout() const { + const auto max_retransmissions = dtls_maximum_retransmissions(); + if(!max_retransmissions.has_value()) { + return std::nullopt; + } + + // The DTLS retransmission timer waits once after the initial flight and once + // after each retransmission. The wait starts at dtls_initial_timeout() and + // doubles with every retransmission until it reaches dtls_maximum_timeout(). + size_t timeout = dtls_initial_timeout(); + + // Technically, a user could configure a 0ms initial timer, which renders the + // calculations below meaningless. We disable the flight timer in this case. + if(timeout == 0) { + return std::nullopt; + } + + const size_t max_timeout = dtls_maximum_timeout(); + + const auto saturating_add = [](std::optional a, size_t b) -> std::optional { + // We want to make sure that the overall timeout stays representable as + // a std::chrono::milliseconds which uses a signed type internally. + constexpr auto max = static_cast(std::chrono::milliseconds::max().count()); + + // TODO(C++23): use std::optional::transform + if(!a.has_value()) { + return std::nullopt; + } + + auto result = checked_add(a.value(), b); + if(!result.has_value() || result > max) { + return std::nullopt; + } + + return result; + }; + + const auto next_timeout = [&](size_t current_timeout) { + return (current_timeout > max_timeout / 2) ? max_timeout : 2 * current_timeout; + }; + + std::optional total = timeout; + size_t retransmissions = 0; + + // Exponential backoff until the timeout hits the cap + while(retransmissions < *max_retransmissions && timeout < max_timeout) { + timeout = next_timeout(timeout); + total = saturating_add(total, timeout); + ++retransmissions; + } + + // All remaining retransmissions wait for the capped timeout + const size_t remaining = *max_retransmissions - retransmissions; + const size_t tail = checked_mul(remaining, max_timeout).value_or(std::numeric_limits::max()); + total = saturating_add(total, tail); + + // The retransmission timer re-arms itself relative to when each expiry was + // actually handled, so scheduling latency accumulates over the schedule and + // it ends later than the sum above. Add one more interval as a margin, so + // that the retransmission timer reliably expires before the flight timer. + const size_t margin = next_timeout(timeout); + return saturating_add(total, margin); +} + +size_t Policy::dtls_acknowledgement_delay() const { + return std::max(dtls_initial_timeout() / 4, 25); +} + // Generous next to the one or two a legitimate cookie-secret rotation can // produce, while still bounding a forged stream. std::optional Policy::dtls_maximum_hello_verify_requests() const { @@ -550,6 +631,30 @@ size_t Policy::dtls_default_mtu() const { return 1280 - 40 - 8; } +size_t Policy::dtls_maximum_queued_acknowledgements() const { + // Matches BoringSSL's DTLS_MAX_ACK_BUFFER. + // Considering any reasonable DTLS configuration, there should be plenty of + // leeway for the expected amount of exchanged handshake records. + return 32; +} + +size_t Policy::dtls_maximum_deprotection_failures() const { + // RFC 9147 4.5.3 + // For AEAD_AES_128_GCM, AEAD_AES_256_GCM, and AEAD_CHACHA20_POLY1305, the + // limit on the number of records that fail authentication is 2^36. [...] + // For AEAD_AES_128_CCM, the limit on the number of records that fail + // authentication is 2^23.5 [...]. + // The AEAD_AES_128_CCM_8 AEAD, [...], does not have a limit on the number + // of records that fail authentication that both limits the probability of + // forgery by the same amount and does not expose implementations to the + // risk of denial of service [...]. Therefore, TLS_AES_128_CCM_8_SHA256 + // MUST NOT be used in DTLS without additional safeguards against forgery. + // + // We take the lowest of these limits, and assume that the CCM_8 AEAD is not + // used by anyone who would want to use this default policy. + return 1 << 23; +} + std::vector Policy::srtp_profiles() const { return std::vector(); } diff --git a/src/lib/tls/tls_policy.h b/src/lib/tls/tls_policy.h index 7c6faa03580..c768057b22e 100644 --- a/src/lib/tls/tls_policy.h +++ b/src/lib/tls/tls_policy.h @@ -603,6 +603,52 @@ class BOTAN_PUBLIC_API(2, 0) Policy /* NOLINT(*-special-member-functions) */ { */ virtual size_t dtls_maximum_timeout() const; + /** + * @return the maximum time in milliseconds that a DTLS 1.3 interaction + * may stall after we sent a flight: unless the peer completes its + * response flight or acknowledges the flight that ends the interaction + * within this time, the connection is abandoned. nullopt disables the + * flight timeout. + * + * The timeout is armed when a flight is sent and is not reset by progress + * afterwards (neither by retransmissions of the flight nor by partial + * progress of the peer's next flight): it bounds the whole interaction. + * + * In DTLS 1.3, once a peer acknowledges all records of an outstanding + * flight (explicitly via an ACK record or implicitly by sending part of + * the next flight), retransmissions stop (RFC 9147 7.1/7.2). Without a + * flight timeout, a peer that acknowledges a flight and never completes + * its response can leave the handshake stuck indefinitely. + * + * By default, this returns the total duration of the retransmission + * schedule implied by dtls_initial_timeout(), dtls_maximum_timeout(), and + * dtls_maximum_retransmissions(), plus one more retransmission interval + * as a margin. Returns nullopt if dtls_maximum_retransmissions() returns + * nullopt or dtls_initial_timeout() is zero. + * + * @note Only applies for DTLS 1.3 associations. + */ + virtual std::optional dtls_flight_timeout() const; + + /** + * DTLS 1.3 defines a record acknowledgement mechanism to allow the peer to + * acknowledge incoming handshake message fragments. In order to coalesce + * multiple incoming handshake records into a single acknowledgement, they + * are sent with a delay started on the first incoming record. If the + * peer's entire flight is received before the delay expires, no + * acknowledgement is sent and our response flight implicitly acknowledges + * the peer's flight. + * + * Default: 25% of dtls_initial_timeout (see RFC 9147 Section 7.1) or 25ms + * as a lower bound. + * + * @note Only applies for DTLS 1.3 associations. + * + * @return the delay in milliseconds from the first received handshake + * record until emitting an acknowledgement record. + */ + virtual size_t dtls_acknowledgement_delay() const; + /** * @return the maximum number of times a DTLS handshake flight will be * retransmitted on timeouts before the handshake is abandoned. After this @@ -631,6 +677,29 @@ class BOTAN_PUBLIC_API(2, 0) Policy /* NOLINT(*-special-member-functions) */ { */ virtual std::optional dtls_maximum_hello_verify_requests() const; + /** + * @return the maximum number of queued DTLS record acknowledgements. + * + * Dropping ACKs won't cause a connection to fail, but may result in + * spurious retransmissions. This is used to cap the amount of consumed + * memory for the stored ACK information. + * + * Default: 32 + * + * @note Only applies for DTLS 1.3 associations. + */ + virtual size_t dtls_maximum_queued_acknowledgements() const; + + /** + * @return the maximum number of allowed record deprotection failures + * + * If a DTLS 1.3 association receives more than this many records which + * fail deprotection in a single epoch, the association is terminated. + * + * TODO: enforce this in DTLS 1.2 as well + */ + virtual size_t dtls_maximum_deprotection_failures() const; + /** * @return the maximum size of a single handshake message, in bytes. * Messages larger than this will be rejected prior to processing. @@ -863,7 +932,7 @@ class BOTAN_PUBLIC_API(2, 0) BSI_TR_02102_2 : public Policy { }; /** -* Policy for DTLS. We require DTLS v1.2 and an AEAD mode. +* Policy for DTLS. We require DTLS v1.2 or v1.3 and an AEAD mode. */ class BOTAN_PUBLIC_API(2, 0) Datagram_Policy : public Policy { public: @@ -873,7 +942,9 @@ class BOTAN_PUBLIC_API(2, 0) Datagram_Policy : public Policy { bool allow_tls13() const override { return false; } - bool allow_dtls12() const override { return true; } + // We don't enable DTLS 1.2/1.3 explicitly because we assume that the + // default policy (from which we inherit) always enables it when it is + // available in the given build of the library. }; /* @@ -966,8 +1037,16 @@ class BOTAN_PUBLIC_API(2, 0) Text_Policy : public Policy { size_t dtls_maximum_timeout() const override; + std::optional dtls_flight_timeout() const override; + + size_t dtls_acknowledgement_delay() const override; + std::optional dtls_maximum_hello_verify_requests() const override; + size_t dtls_maximum_queued_acknowledgements() const override; + + size_t dtls_maximum_deprotection_failures() const override; + std::optional max_useless_records() const override; bool require_cert_revocation_info() const override; diff --git a/src/lib/tls/tls_text_policy.cpp b/src/lib/tls/tls_text_policy.cpp index 167ee2ef795..57baa14bc18 100644 --- a/src/lib/tls/tls_text_policy.cpp +++ b/src/lib/tls/tls_text_policy.cpp @@ -213,6 +213,24 @@ size_t Text_Policy::dtls_maximum_timeout() const { return get_len("dtls_maximum_timeout", Policy::dtls_maximum_timeout()); } +std::optional Text_Policy::dtls_flight_timeout() const { + const std::string v = get_str("dtls_flight_timeout"); + + if(v.empty()) { + return Policy::dtls_flight_timeout(); + } + + if(v == "none") { + return std::nullopt; + } + + return to_u32bit(v); +} + +size_t Text_Policy::dtls_acknowledgement_delay() const { + return get_len("dtls_acknowledgement_delay", Policy::dtls_acknowledgement_delay()); +} + std::optional Text_Policy::dtls_maximum_hello_verify_requests() const { const std::string v = get_str("dtls_maximum_hello_verify_requests"); @@ -227,6 +245,14 @@ std::optional Text_Policy::dtls_maximum_hello_verify_requests() const { return to_u32bit(v); } +size_t Text_Policy::dtls_maximum_queued_acknowledgements() const { + return get_len("dtls_maximum_queued_acknowledgements", Policy::dtls_maximum_queued_acknowledgements()); +} + +size_t Text_Policy::dtls_maximum_deprotection_failures() const { + return get_len("dtls_maximum_deprotection_failures", Policy::dtls_maximum_deprotection_failures()); +} + std::optional Text_Policy::max_useless_records() const { const std::string v = get_str("max_useless_records"); diff --git a/src/lib/tls/tls_version.cpp b/src/lib/tls/tls_version.cpp index 3e0794a3af3..53c5f018d67 100644 --- a/src/lib/tls/tls_version.cpp +++ b/src/lib/tls/tls_version.cpp @@ -32,9 +32,9 @@ Protocol_Version Protocol_Version::latest_tls_version() { } Protocol_Version Protocol_Version::latest_dtls_version() { - // Note: DTLS 1.3 is not yet supported, so DTLS 1.2 remains the latest - // DTLS version for the time being. -#if defined(BOTAN_HAS_TLS_12) +#if defined(BOTAN_HAS_DTLS_13) + return Protocol_Version::DTLS_V13; +#elif defined(BOTAN_HAS_TLS_12) return Protocol_Version::DTLS_V12; #else throw Not_Implemented("This build contains no usable DTLS version"); @@ -121,6 +121,12 @@ bool Protocol_Version::known_version() const { } #endif +#if defined(BOTAN_HAS_DTLS_13) + if(m_version == static_cast(Protocol_Version::DTLS_V13)) { + return true; + } +#endif + #if defined(BOTAN_HAS_TLS_12) if(m_version == static_cast(Protocol_Version::TLS_V12)) { return true; diff --git a/src/plzn_shim/expectations.json b/src/plzn_shim/expectations.json index c3bbe2ac7d8..1bbe0b04ffa 100644 --- a/src/plzn_shim/expectations.json +++ b/src/plzn_shim/expectations.json @@ -1,5 +1,10 @@ { "schema_version": 1, "overrides": {}, - "patterns": [] + "patterns": [ + { + "pattern": "dtls13/client-retransmits-final-flight-after-live-mtu-change", + "skip": "Botan's plzn shim does not implement plzn's set_mtu ('M') opcode for live MTU changes" + } + ] } diff --git a/src/plzn_shim/plzn_shim.cpp b/src/plzn_shim/plzn_shim.cpp index ef3362e63a3..55e1a5a9d3b 100644 --- a/src/plzn_shim/plzn_shim.cpp +++ b/src/plzn_shim/plzn_shim.cpp @@ -278,6 +278,10 @@ class Shim_Policy final : public Botan::TLS::Policy { return m_cfg.is_dtls() && version_in_range(Botan::TLS::Protocol_Version::DTLS_V12); } + bool allow_dtls13() const override { + return m_cfg.is_dtls() && version_in_range(Botan::TLS::Protocol_Version::DTLS_V13); + } + // Accept peer-initiated renegotiation when the runner asks for it (these // are the real Botan policy virtuals; the library defaults are false). A // server honours a client's renegotiation ClientHello; a client honours a @@ -348,9 +352,7 @@ class Shim_Policy final : public Botan::TLS::Policy { // `uut { min_key_update_interval_ms: N }`: a peer KeyUpdate arriving sooner // than N ms after the previous one is rejected with unexpected_message // (a solicited reciprocation is exempt); 0 disables the rate limit. - uint64_t minimum_key_update_interval_ms() const override { - return m_cfg.min_key_update_interval_ms.value_or(Botan::TLS::Policy::minimum_key_update_interval_ms()); - } + uint64_t minimum_key_update_interval_ms() const override { return m_cfg.min_key_update_interval_ms.value_or(0); } size_t new_session_tickets_upon_handshake_success() const override { return m_cfg.session_tickets.value_or(Botan::TLS::Policy::new_session_tickets_upon_handshake_success()); @@ -364,6 +366,18 @@ class Shim_Policy final : public Botan::TLS::Policy { return m_cfg.dtls_max_timeout_ms.value_or(Botan::TLS::Policy::dtls_maximum_timeout()); } + // The blanket flight timeout is opt-in for plzn: the retransmission and + // ACK tests expect that no timer is armed once a flight was + // acknowledged, which the default (derived) flight timeout would + // violate. Cases that want the guard set dtls_flight_timeout_ms + // explicitly; a value of 0 arms a guard that fires immediately. + std::optional dtls_flight_timeout() const override { + if(m_cfg.dtls_flight_timeout_ms.has_value()) { + return static_cast(*m_cfg.dtls_flight_timeout_ms); + } + return std::nullopt; + } + std::optional dtls_maximum_retransmissions() const override { if(m_cfg.dtls_max_retransmissions.has_value()) { return static_cast(*m_cfg.dtls_max_retransmissions); @@ -379,7 +393,23 @@ class Shim_Policy final : public Botan::TLS::Policy { } bool dtls_server_require_cookie_exchange() const override { - return m_cfg.dtls_require_cookie.value_or(Botan::TLS::Policy::dtls_server_require_cookie_exchange()); + if(m_cfg.dtls_require_cookie.has_value()) { + return *m_cfg.dtls_require_cookie; + } + + // plzn's DTLS 1.3 corpus assumes a cookieless server by default: its + // reference implementation (BoringSSL) has no DTLS 1.3 cookie exchange, + // and the tests that exercise the cookie flow opt in via + // `dtls_require_cookie`. RFC 9147 11 merely recommends ("SHOULD use") + // the exchange, so declining it is a valid server posture. + // + // DTLS 1.2 keeps the library default (HelloVerifyRequest): several + // dtls12 tests require the exchange without setting the knob. + if(m_cfg.requests_dtls13()) { + return false; + } + + return Botan::TLS::Policy::dtls_server_require_cookie_exchange(); } bool allow_dtls_epoch0_restart() const override { @@ -1248,9 +1278,11 @@ int main(int argc, char* argv[]) { return 2; } +#if !defined(BOTAN_HAS_DTLS_13) if(cfg.requests_dtls13()) { - plzn::report_unsupported("versions", "Botan does not currently implement DTLS 1.3"); + plzn::report_unsupported("versions", "Botan does not support DTLS 1.3 in this build"); } +#endif if(!cfg.is_dtls() && (cfg.min_version.value_or(0x0303) < 0x0303 || cfg.max_version.value_or(0x0304) < 0x0303)) { plzn::report_unsupported("versions", "Botan 3 does not implement TLS 1.0 or TLS 1.1"); } diff --git a/src/scripts/ci/gha_linux_packages.py b/src/scripts/ci/gha_linux_packages.py index ff2f0767983..fdf015cb81f 100755 --- a/src/scripts/ci/gha_linux_packages.py +++ b/src/scripts/ci/gha_linux_packages.py @@ -31,7 +31,7 @@ def gha_linux_packages(target, compiler): if target.startswith('valgrind'): packages.append('valgrind') - if target in ['shared', 'coverage', 'amalgamation', 'sanitizer', 'tlsanvil', 'examples', 'clang-tidy', 'no_tls12', 'no_tls13']: + if target in ['shared', 'coverage', 'amalgamation', 'sanitizer', 'tlsanvil', 'examples', 'clang-tidy', 'no_dtls13', 'no_tls12', 'no_tls13']: packages.append('libboost-dev') if target in ['clang']: diff --git a/src/scripts/ci_build.py b/src/scripts/ci_build.py index 94d8b98199c..fcf04986e37 100755 --- a/src/scripts/ci_build.py +++ b/src/scripts/ci_build.py @@ -65,6 +65,7 @@ def known_targets(): 'limbo', 'minimized', 'nist', + 'no_dtls13', 'no_pcurves', 'no_tls12', 'optional-rngs', @@ -137,7 +138,7 @@ def build_targets(target, target_os): if target not in ['examples', 'limbo', 'hybrid-tls13-interop-test', 'strubbing', 'wycheproof', 'acvp', 'plzn']: yield 'tests' - if target in ['coverage', 'no_tls12', 'no_tls13']: + if target in ['coverage', 'no_dtls13', 'no_tls12', 'no_tls13']: yield 'bogo_shim' if target in ['sanitizer'] and target_os not in ['windows']: yield 'bogo_shim' @@ -255,6 +256,9 @@ def sanitize_kv(some_string): if target in ['no_pcurves']: flags += ['--disable-modules=pcurves_impl'] + if target in ['no_dtls13']: + flags += ['--disable-modules=dtls13'] + if target in ['no_tls12']: flags += ['--disable-modules=tls12'] @@ -465,7 +469,7 @@ def sanitize_kv(some_string): flags += ['--with-commoncrypto'] def add_boost_support(target, target_os): - if target in ['coverage', 'amalgamation', 'no_tls12', 'no_tls13']: + if target in ['coverage', 'amalgamation', 'no_dtls13', 'no_tls12', 'no_tls13']: return True if target == 'sanitizer' and target_os == 'linux': @@ -955,15 +959,18 @@ def main(args=None): 'src/scripts/run_tests_under_valgrind.py'] + valgrind_script_options) - if target in ['coverage', 'sanitizer', 'no_tls12', 'no_tls13'] and options.os != 'windows': + if target in ['coverage', 'sanitizer', 'no_dtls13', 'no_tls12', 'no_tls13'] and options.os != 'windows': if not options.boringssl_dir: raise Exception('%s build needs --boringssl-dir' % (target)) runner_dir = os.path.abspath(os.path.join(options.boringssl_dir, 'ssl', 'test', 'runner')) - if target == 'no_tls12': + if target == 'no_dtls13': + shim_config = os.path.abspath(os.path.join(root_dir, 'src', 'bogo_shim', 'config_no_dtls13.json')) + extra_args = [] + elif target == 'no_tls12': shim_config = os.path.abspath(os.path.join(root_dir, 'src', 'bogo_shim', 'config_no_tls12.json')) - extra_args = ['-skip-tls12', '-skip-dtls'] + extra_args = ['-skip-tls12'] elif target == 'no_tls13': shim_config = os.path.abspath(os.path.join(root_dir, 'src', 'bogo_shim', 'config_no_tls13.json')) extra_args = ['-skip-tls13'] diff --git a/src/tests/test_dtls12.cpp b/src/tests/test_dtls12.cpp index cd4ea076234..e4b7a8234b3 100644 --- a/src/tests/test_dtls12.cpp +++ b/src/tests/test_dtls12.cpp @@ -200,6 +200,8 @@ class DTLS12_Policy : public Botan::TLS::Policy { bool allow_dtls12() const override { return true; } + bool allow_dtls13() const override { return false; } + private: bool m_allow_tls12; }; diff --git a/src/tests/test_tls_dtls13_channel_io.cpp b/src/tests/test_tls_dtls13_channel_io.cpp new file mode 100644 index 00000000000..33b980d8adb --- /dev/null +++ b/src/tests/test_tls_dtls13_channel_io.cpp @@ -0,0 +1,1795 @@ +/* +* Integration tests for the DTLS 1.3 Channel_IO +* (C) 2026 Jack Lloyd +* 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include "tests.h" + +#if defined(BOTAN_HAS_DTLS_13) + + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + +namespace Botan_Tests { + +namespace { + +namespace TLS = Botan::TLS; + +constexpr auto epoch_appdata_0 = TLS::EpochNumber::create(3); +constexpr auto epoch_appdata_1 = TLS::EpochNumber::create(4); + +class Mock_Callbacks final : public TLS::Callbacks { + public: + void tls_emit_data(std::span data) override { m_datagrams.emplace_back(data.begin(), data.end()); } + + void tls_record_received(uint64_t /*seq_no*/, std::span /*data*/) override { + throw Botan::Invalid_State("Channel_IO does not invoke tls_record_received"); + } + + void tls_alert(TLS::Alert /*alert*/) override {} + + uint64_t tls_current_monotonic_clock_ms() override { return m_now_ms; } + + void tls_register_deferred_operation(uint64_t monotonic_delay_ms, std::function op) override { + m_registered_delays.push_back(monotonic_delay_ms); + m_deferred_operations.push_back({.deadline_ms = m_now_ms + monotonic_delay_ms, .op = std::move(op)}); + } + + /// Advances the virtual clock and runs all deferred operations that became due + void advance_clock(uint64_t delta_ms) { + m_now_ms += delta_ms; + + // Due operations may register new deferred operations (e.g. the + // retransmission timer re-arms itself), hence collect them first. + std::vector> due_ops; + std::erase_if(m_deferred_operations, [&](Deferred_Operation& op) { + if(op.deadline_ms <= m_now_ms) { + due_ops.emplace_back(std::move(op.op)); + return true; + } + return false; + }); + + for(const auto& op : due_ops) { + op(); + } + } + + /// In DTLS, each invocation of tls_emit_data() carries exactly one datagram + const std::vector>& datagrams() const { return m_datagrams; } + + void clear_datagrams() { m_datagrams.clear(); } + + /// Hands out all datagrams emitted so far and forgets about them + std::vector> take_datagrams() { return std::exchange(m_datagrams, {}); } + + /// Delays of all deferred operations ever registered, in order of registration + const std::vector& registered_delays() const { return m_registered_delays; } + + private: + struct Deferred_Operation { + uint64_t deadline_ms; + std::function op; + }; + + uint64_t m_now_ms = 0; + std::vector m_deferred_operations; + std::vector m_registered_delays; + std::vector> m_datagrams; +}; + +std::shared_ptr make_policy(std::optional mtu = {}, + std::optional initial_timeout_ms = {}, + std::optional maximum_deprotection_failures = {}) { + class Test_Policy final : public TLS::Policy { + public: + Test_Policy(std::optional mtu, + std::optional initial_timeout_ms, + std::optional maximum_deprotection_failures) : + m_mtu(mtu), + m_initial_timeout_ms(initial_timeout_ms), + m_maximum_deprotection_failures(maximum_deprotection_failures) {} + + size_t dtls_default_mtu() const override { return m_mtu.value_or(Policy::dtls_default_mtu()); } + + size_t dtls_initial_timeout() const override { + return m_initial_timeout_ms.value_or(Policy::dtls_initial_timeout()); + } + + size_t dtls_maximum_deprotection_failures() const override { + return m_maximum_deprotection_failures.value_or(Policy::dtls_maximum_deprotection_failures()); + } + + private: + std::optional m_mtu; + std::optional m_initial_timeout_ms; + std::optional m_maximum_deprotection_failures; + }; + + return std::make_shared(mtu, initial_timeout_ms, maximum_deprotection_failures); +} + +/// Cipher state with handshake traffic keys derived from a synthetic shared +/// secret. Client and server states created by this are compatible. +std::shared_ptr handshake_traffic_cipher_state(TLS::Connection_Side side) { + const auto cipher = TLS::Ciphersuite::from_name("AES_128_GCM_SHA256").value(); + return TLS::Cipher_State::init_with_server_hello( + side, TLS::TLS_Flavor::DTLS, Botan::secure_vector(32, 0x00), cipher, std::vector(32, 0x00), {}); +} + +/// Cipher state of a completed handshake: application traffic keys (epoch 3) have +/// been derived. Client and server states created by this are compatible. +std::shared_ptr application_traffic_cipher_state(TLS::Connection_Side side) { + auto cipher_state = handshake_traffic_cipher_state(side); + const std::vector transcript_hash(32, 0x00); + cipher_state->advance_with_server_finished(transcript_hash); + cipher_state->advance_with_client_finished(transcript_hash); + return cipher_state; +} + +enum class Keys : uint8_t { None, HandshakeTraffic, ApplicationTraffic }; + +/// A DTLS Channel_IO along with its callbacks and (optional) cipher state +struct Endpoint { + std::shared_ptr callbacks; + std::shared_ptr io; + std::shared_ptr cipher_state; +}; + +struct Endpoints { + std::shared_ptr policy; + Endpoint client; + Endpoint server; +}; + +Endpoint make_endpoint(TLS::Connection_Side side, + const std::shared_ptr& policy, + std::shared_ptr cipher_state) { + auto callbacks = std::make_shared(); + auto io = TLS::Channel_IO::create(side, TLS::TLS_Flavor::DTLS, policy, callbacks); + if(cipher_state != nullptr) { + // Epoch steering: not done by Channel_IO but necessary for the tests + io->set_cipher_state(cipher_state); + } + return {.callbacks = std::move(callbacks), .io = std::move(io), .cipher_state = std::move(cipher_state)}; +} + +Endpoints make_endpoints(std::shared_ptr policy, Keys keys = Keys::None) { + const auto cipher_state = [&](TLS::Connection_Side side) -> std::shared_ptr { + switch(keys) { + case Keys::None: + return nullptr; + case Keys::HandshakeTraffic: + return handshake_traffic_cipher_state(side); + case Keys::ApplicationTraffic: + return application_traffic_cipher_state(side); + } + BOTAN_ASSERT_UNREACHABLE(); + }; + + auto client = make_endpoint(TLS::Connection_Side::Client, policy, cipher_state(TLS::Connection_Side::Client)); + auto server = make_endpoint(TLS::Connection_Side::Server, policy, cipher_state(TLS::Connection_Side::Server)); + + // The tests model a server that already received and completed the peer's + // first flight (the ClientHello) and is about to respond or has moved on to + // post-handshake interactions. Reporting the completed flight brings the + // server's exchange bookkeeping into that state. + server.io->notify_received_complete_flight(TLS::Expected_Response::Flight); + + return {.policy = std::move(policy), .client = std::move(client), .server = std::move(server)}; +} + +std::optional make_transcript_hash() { + return TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); +} + +/** + * Pulls events off the channel until no more are pending. + * Returns the events along with the terminal BytesNeeded value. + */ +struct Drained_Events { + std::vector events; + TLS::BytesNeeded bytes_needed = 0; +}; + +Drained_Events drain_events(TLS::Channel_IO& io, + std::optional& transcript_hash, + bool handshake_complete) { + Drained_Events drained; + while(true) { + auto event = io.next_pending_event(transcript_hash, handshake_complete); + if(std::holds_alternative(event)) { + drained.bytes_needed = std::get(event); + return drained; + } + drained.events.emplace_back(std::move(event)); + } +} + +/// A handshake message with arbitrary content. Channel_IO sends messages +/// without parsing them, so the content does not need to be well-formed. +TLS::Flight::Message_Info synthetic_message(TLS::Handshake_Type type, TLS::EpochNumber epoch, size_t size) { + std::vector content(size); + for(size_t i = 0; i < size; ++i) { + content[i] = static_cast(static_cast(type) + i); + } + + return { + .wire_type = type, + .epoch = epoch, + .header = TLS::TLS_Handshake_Layer::prepare_header(type, size), + .serialized = TLS::SerializedHandshakeMessage(std::move(content)), + }; +} + +void send_flight(const Endpoint& sender, + const std::vector& flight, + TLS::Expected_Response expected) { + sender.io->send(std::vector(flight.begin(), flight.end()), expected); +} + +/// Wire view of handshake messages as decoded by the peer +struct Received_Fragment { + TLS::Handshake_Type type; // NOLINT(*-non-private-member-variables-in-classes) + size_t message_length; // NOLINT(*-non-private-member-variables-in-classes) + uint16_t message_seq; // NOLINT(*-non-private-member-variables-in-classes) + size_t offset; // NOLINT(*-non-private-member-variables-in-classes) + std::vector bytes; // NOLINT(*-non-private-member-variables-in-classes) + + bool operator==(const Received_Fragment&) const = default; +}; + +struct Received_Record { + TLS::Record_Type type; // NOLINT(*-non-private-member-variables-in-classes) + TLS::EpochNumber epoch; // NOLINT(*-non-private-member-variables-in-classes) + uint64_t sequence_number; // NOLINT(*-non-private-member-variables-in-classes) + size_t payload_length; // NOLINT(*-non-private-member-variables-in-classes) + std::vector fragments; // NOLINT(*-non-private-member-variables-in-classes) + std::vector acknowledged; // NOLINT(*-non-private-member-variables-in-classes) + Botan::secure_vector payload; // NOLINT(*-non-private-member-variables-in-classes) + + TLS::RecordNumber number() const { return {.epoch = epoch, .sequence_number = sequence_number}; } +}; + +struct Received_Datagram { + size_t length; + std::vector records; +}; + +uint32_t load_be24(std::span bytes) { + return Botan::make_uint32(0, bytes[0], bytes[1], bytes[2]); +} + +std::vector parse_fragments(std::span record_payload) { + std::vector fragments; + Botan::BufferSlicer bs(record_payload); + while(!bs.empty()) { + // RFC 9147 5.2 + // msg_type(1) || length(3) || message_seq(2) || fragment_offset(3) || fragment_length(3) + const auto header = bs.take(); + fragments.push_back({ + .type = static_cast(header[0]), + .message_length = load_be24(header.subspan<1, 3>()), + .message_seq = Botan::load_be(header.subspan<4, 2>()), + .offset = load_be24(header.subspan<6, 3>()), + .bytes = bs.copy_as_vector(load_be24(header.subspan<9, 3>())), + }); + } + return fragments; +} + +/// A record as found in a datagram, before any deprotection +struct Raw_Record { + bool is_protected; + std::span bytes; +}; + +/// Splits a datagram into its consecutive records (RFC 9147 4.3) +std::vector split_records(std::span datagram) { + std::vector records; + Botan::BufferSlicer bs(datagram); + while(!bs.empty()) { + const size_t start = datagram.size() - bs.remaining(); + // RFC 9147 4.1: DTLSCiphertext records start with the bits 001 + const bool is_protected = (bs.peek_byte() & 0b11100000) == 0b00100000; + if(is_protected) { + const auto header = TLS::UnifiedHeader_DTLS::parse(bs, std::nullopt /* no CID */); + bs.skip(header.length.value_or(bs.remaining())); + } else { + const auto header = TLS::PlaintextHeader_DTLS::parse(bs); + bs.skip(header.length); + } + const size_t end = datagram.size() - bs.remaining(); + records.push_back({.is_protected = is_protected, .bytes = datagram.subspan(start, end - start)}); + } + return records; +} + +/** + * Decodes @p datagrams the way the peer's record layer would. The peer's + * cipher state is only used for records that are actually protected: a peer + * that already holds handshake traffic keys discards plaintext records of an + * earlier epoch (RFC 9147 4.2.1), but the first server flight's ServerHello + * arrives before the peer derived these keys. + */ +std::vector decode_datagrams(Test::Result& result, + const std::vector>& datagrams, + TLS::Cipher_State* peer_cipher_state) { + TLS::DTLS_Record_Layer peer{Botan::TLS::Policy{}}; + + std::vector decoded; + for(const auto& datagram : datagrams) { + auto& received = decoded.emplace_back(Received_Datagram{.length = datagram.size(), .records = {}}); + for(const auto& raw_record : split_records(datagram)) { + result.require("peer accepts the record", peer.copy_data(raw_record.bytes, false /* fail loudly */)); + auto record = peer.next_record(raw_record.is_protected ? peer_cipher_state : nullptr); + + if(const auto* handshake_record = std::get_if(&record)) { + received.records.push_back({ + .type = TLS::Record_Type::Handshake, + .epoch = handshake_record->epoch.value(), + .sequence_number = handshake_record->sequence_number.value(), + .payload_length = handshake_record->payload.size(), + .fragments = parse_fragments(handshake_record->payload), + .acknowledged = {}, + .payload = {}, + }); + } else if(const auto* ack_record = std::get_if(&record)) { + const TLS::ACKs acks(ack_record->payload); + received.records.push_back({ + .type = TLS::Record_Type::ACK, + .epoch = ack_record->epoch.value(), + .sequence_number = ack_record->sequence_number.value(), + .payload_length = ack_record->payload.size(), + .fragments = {}, + .acknowledged = {acks.record_numbers().begin(), acks.record_numbers().end()}, + .payload = {}, + }); + } else if(const auto* data_record = std::get_if(&record)) { + received.records.push_back({ + .type = TLS::Record_Type::ApplicationData, + .epoch = data_record->epoch.value(), + .sequence_number = data_record->sequence_number.value(), + .payload_length = data_record->payload.size(), + .fragments = {}, + .acknowledged = {}, + .payload = std::move(data_record->payload), + }); + } else { + result.test_failure("peer received a handshake, ACK or application data record"); + } + } + } + return decoded; +} + +/// Bytes added to a record's payload on the wire (header plus protection overhead) +size_t record_overhead(TLS::EpochNumber epoch, const TLS::Policy& policy, const TLS::Cipher_State* cipher_state) { + if(epoch.is_unprotected()) { + return TLS::DTLS_HEADER_SIZE; + } + + BOTAN_ASSERT_NONNULL(cipher_state); + constexpr size_t content_type_length = 1; + return TLS::UnifiedHeader_DTLS::expected_length(policy, std::nullopt /* no CID */) + content_type_length + + cipher_state->encrypt_output_length(0); +} + +/** + * Sends @p flight from the server, decodes the emitted datagrams on the + * client's side and checks invariants that must hold for any flight: + * + * - every datagram fits into the MTU, + * - every record carries exactly the overhead mandated by its epoch, + * - fragments are only placed into records of their message's epoch, and + * - the reassembled messages equal the input. + * + * This assumes that the server did not send any handshake messages before, + * i.e. the message_seq of each message equals its index in @p flight. + */ +std::vector transmit_server_flight(Test::Result& result, + const Endpoints& endpoints, + const std::vector& flight) { + send_flight(endpoints.server, flight, TLS::Expected_Response::Flight); + auto wire = decode_datagrams(result, endpoints.server.callbacks->datagrams(), endpoints.client.cipher_state.get()); + + const auto& policy = *endpoints.policy; + std::vector> reassembled(flight.size()); + + for(const auto& datagram : wire) { + result.test_sz_lte("datagram fits into the MTU", datagram.length, policy.dtls_default_mtu()); + + size_t expected_datagram_length = 0; + for(const auto& record : datagram.records) { + result.test_enum_eq("record is a handshake record", record.type, TLS::Record_Type::Handshake); + expected_datagram_length += + record_overhead(record.epoch, policy, endpoints.server.cipher_state.get()) + record.payload_length; + + for(const auto& fragment : record.fragments) { + result.require("fragment belongs to a message of the flight", fragment.message_seq < flight.size()); + const auto& message = flight[fragment.message_seq]; + result.test_enum_eq("fragment has the message's type", fragment.type, message.wire_type); + result.test_sz_eq("fragment has the message's length", fragment.message_length, message.serialized.size()); + result.test_is_true("fragment is in a record of the message's epoch", record.epoch == message.epoch); + + auto& message_bytes = reassembled[fragment.message_seq]; + result.test_sz_eq("fragments are sent in order", fragment.offset, message_bytes.size()); + message_bytes.insert(message_bytes.end(), fragment.bytes.begin(), fragment.bytes.end()); + } + } + + result.test_sz_eq( + "datagram consists of records with their per-epoch overhead", datagram.length, expected_datagram_length); + } + + for(size_t i = 0; i < flight.size(); ++i) { + result.test_bin_eq("reassembled message equals the input", reassembled[i], flight[i].serialized.get()); + } + + return wire; +} + +bool contains(std::span numbers, const TLS::RecordNumber& number) { + return std::find_if(numbers.begin(), numbers.end(), [&](const auto& rn) { return rn == number; }) != numbers.end(); +} + +/// The numbers of all records of @p type in @p wire in the order they were sent +std::vector record_numbers(const std::vector& wire, + TLS::Record_Type type = TLS::Record_Type::Handshake) { + std::vector numbers; + for(const auto& datagram : wire) { + for(const auto& record : datagram.records) { + if(record.type == type) { + numbers.push_back(record.number()); + } + } + } + return numbers; +} + +size_t count_records(const std::vector& wire, TLS::Record_Type type) { + return record_numbers(wire, type).size(); +} + +/// All handshake fragments in @p wire, except those in records listed in @p excluded_records +std::vector fragments_of(const std::vector& wire, + std::span excluded_records = {}) { + std::vector fragments; + for(const auto& datagram : wire) { + for(const auto& record : datagram.records) { + if(record.type == TLS::Record_Type::Handshake && !contains(excluded_records, record.number())) { + fragments.insert(fragments.end(), record.fragments.begin(), record.fragments.end()); + } + } + } + return fragments; +} + +/// The record numbers acknowledged by all ACK records in @p wire +std::vector acknowledged_by(const std::vector& wire) { + std::vector numbers; + for(const auto& datagram : wire) { + for(const auto& record : datagram.records) { + numbers.insert(numbers.end(), record.acknowledged.begin(), record.acknowledged.end()); + } + } + return numbers; +} + +/** + * A DTLS server under test (with handshake traffic keys) and a simulated + * client peer. The peer is a second Channel_IO, such that its fragments and + * retransmissions are real wire data, and it crafts ACK records with its + * cipher state. Server-side output is always decoded the way the peer would. + * + * The timing is chosen such that all timers are distinct: the server's + * retransmission timer fires after 400ms, its ACK timer after 100ms. + */ +class Exchange { + public: + static constexpr size_t mtu = 400; + static constexpr size_t initial_timeout_ms = 400; + static constexpr size_t ack_timeout_ms = initial_timeout_ms / 4; + + public: + explicit Exchange(Test::Result& result, + Keys keys = Keys::HandshakeTraffic, + std::optional maximum_deprotection_failures = {}) : + m_result(result), + m_endpoints(make_endpoints(make_policy(mtu, initial_timeout_ms, maximum_deprotection_failures), keys)), + m_transcript_hash(make_transcript_hash()), + m_handshake_complete(keys == Keys::ApplicationTraffic), + m_client_record_layer{*m_endpoints.policy} {} + + const Endpoint& server() const { return m_endpoints.server; } + + const Endpoint& client() const { return m_endpoints.client; } + + /// The server learns that its peer indeed talks DTLS 1.3 (e.g. after receiving a ClientHello) + void commit() const { server().io->notify_protocol_version_committed(); } + + static std::vector default_server_flight() { + using enum TLS::Handshake_Type; + return { + synthetic_message(ServerHello, TLS::EpochNumber::unprotected(), 90), + synthetic_message(EncryptedExtensions, TLS::EpochNumber::handshake_traffic(), 40), + synthetic_message(Certificate, TLS::EpochNumber::handshake_traffic(), 900), + synthetic_message(CertificateVerify, TLS::EpochNumber::handshake_traffic(), 80), + synthetic_message(Finished, TLS::EpochNumber::handshake_traffic(), 32), + }; + } + + /// Sends a flight (by default one spanning several datagrams and both + /// epochs) and returns what the peer receives + std::vector send_server_flight( + const std::vector& flight = default_server_flight(), + TLS::Expected_Response expected = TLS::Expected_Response::Flight) { + send_flight(server(), flight, expected); + return take_server_output(); + } + + /// Whatever the server emitted since the last call, as the peer sees it + std::vector take_server_output() { + return decode_datagrams(m_result, server().callbacks->take_datagrams(), client().cipher_state.get()); + } + + /** + * Advances the server's clock and runs the timers that became due. + * + * @returns the number of deferred operations scheduled in the meantime. + * A retransmission timer that expired without being cancelled + * re-arms itself, even if there is nothing left to retransmit. + */ + size_t advance_server_clock(uint64_t delta_ms) const { + const auto& delays = server().callbacks->registered_delays(); + const size_t registered_before = delays.size(); + server().callbacks->advance_clock(delta_ms); + return delays.size() - registered_before; + } + + /// The peer sends a handshake message of @p size bytes (by default protected with handshake traffic keys) + std::vector> client_sends( + TLS::Handshake_Type type, size_t size, TLS::EpochNumber epoch = TLS::EpochNumber::handshake_traffic()) const { + // The synthetic messages sent here do not solicit a response flight; + // the server's reactions are driven by the tests directly. + send_flight(client(), {synthetic_message(type, epoch, size)}, TLS::Expected_Response::None); + return client().callbacks->take_datagrams(); + } + + /// The peer sends a message that does not fit into a single datagram + std::vector> client_sends_fragmented_message() { + auto datagrams = client_sends(TLS::Handshake_Type::Certificate, 2000); + m_result.require("message is fragmented into multiple datagrams", datagrams.size() > 2); + return datagrams; + } + + /// The peer's retransmission timer fires + std::vector> client_retransmits() const { + client().callbacks->advance_clock(initial_timeout_ms); + return client().callbacks->take_datagrams(); + } + + /// Decodes datagrams sent by the peer, e.g. to learn their record numbers + std::vector decode_client_datagrams(const std::vector>& datagrams) { + return decode_datagrams(m_result, datagrams, server().cipher_state.get()); + } + + /// The server receives @p datagram and its pending events are drained + Drained_Events deliver_to_server(std::span datagram) { + server().io->copy_data(datagram); + return drain_events(*server().io, m_transcript_hash, m_handshake_complete); + } + + /// The peer sends a protected ACK for @p records + void client_acknowledges(std::span records) { + const auto& policy = *m_endpoints.policy; + auto* cipher_state = client().cipher_state.get(); + + const TLS::ACKs acks({records.begin(), records.end()}); + const auto max_payload_size = m_client_record_layer.record_payload_size_limit(policy, cipher_state); + + Botan::secure_vector ack_record; + m_client_record_layer.prepare_record( + TLS::Record_Type::ACK, acks.serialize(max_payload_size), policy, cipher_state, ack_record); + m_result.test_is_true("ACK does not surface as an event", deliver_to_server(ack_record).events.empty()); + } + + /// @name Post-handshake traffic (requires Keys::ApplicationTraffic) + /// @{ + + /// The server sends application data and the peer receives it + std::vector send_server_application_data() { + const std::vector payload(20, 0xAA); + server().io->send(payload); + return take_server_output(); + } + + /// The server receives @p count application data records that fail authentication + void server_receives_tampered_records(size_t count) { + for(size_t i = 0; i < count; ++i) { + auto datagrams = client_sends_application_data(); + m_result.require("peer sends a single datagram", datagrams.size() == 1); + + datagrams.front().back() ^= 0x01; + m_result.test_is_true("tampered record is silently discarded", + deliver_to_server(datagrams.front()).events.empty()); + } + } + + /// The peer sends application data + std::vector> client_sends_application_data() const { + const std::vector payload(20, 0xBB); + client().io->send(payload); + return client().callbacks->take_datagrams(); + } + + /** + * The peer sends a KeyUpdate that the server receives and passes on to + * its Channel_IO, just like the channel would do. + * + * @returns the number of the record holding the KeyUpdate + */ + TLS::RecordNumber server_receives_key_update(bool update_requested) { + client().io->update_traffic_keys(update_requested); + const auto datagrams = client().callbacks->take_datagrams(); + m_result.require("peer sends a single datagram", datagrams.size() == 1); + + const auto numbers = record_numbers(decode_client_datagrams(datagrams)); + m_result.require("peer sends a single record", numbers.size() == 1); + + const auto events = deliver_to_server(datagrams.front()).events; + m_result.require("KeyUpdate is the only event", events.size() == 1); + const auto* post_handshake_message = std::get_if(&events.front()); + m_result.require("event is a post-handshake message", post_handshake_message != nullptr); + const auto* key_update = std::get_if(post_handshake_message); + m_result.require("message is a KeyUpdate", key_update != nullptr); + + server().io->handle_key_update(*key_update); + return numbers.front(); + } + + /// The peer processes a KeyUpdate of the server and starts reading with the new keys + void peer_reads_with_updated_keys() const { client().io->handle_key_update(TLS::Key_Update(false)); } + + /// The peer starts writing with the new keys, as if its own KeyUpdate was acknowledged + void peer_writes_with_updated_keys() const { client().cipher_state->update_write_keys(); } + + /// Whether the server still holds the keys to protect records of the given write epoch + bool server_can_write_epoch(TLS::EpochNumber epoch) const { + auto* cipher_state = TLS::as_dtls_cipher_state(server().cipher_state.get()); + BOTAN_ASSERT_NONNULL(cipher_state); + + const std::vector payload(1, 0x00); + Botan::secure_vector out; + try { + cipher_state->protect_record(TLS::Record_Type::ApplicationData, payload, 0, out, epoch); + return true; + } catch(const TLS::TLS_Exception&) { + return false; + } + } + + TLS::EpochNumber server_write_epoch() const { return server().cipher_state->current_write_epoch_number(); } + + TLS::EpochNumber server_read_epoch() const { return server().cipher_state->current_read_epoch_number(); } + + /// @} + + private: + Test::Result& m_result; + Endpoints m_endpoints; + std::optional m_transcript_hash; + bool m_handshake_complete; + TLS::DTLS_Record_Layer m_client_record_layer; +}; + +std::vector send_flights() { + using enum TLS::Handshake_Type; + + constexpr size_t min_fragment_size = TLS::DTLS_Handshake_Layer::FRAGMENT_HEADER_LENGTH + 1; + + const auto packing_up_to_the_mtu = [](const char* name, TLS::EpochNumber epoch) { + return CHECK(name, [=](Test::Result& result) { + const auto keys = (epoch.is_unprotected()) ? Keys::None : Keys::HandshakeTraffic; + const auto endpoints = make_endpoints(make_policy(400), keys); + const size_t mtu = endpoints.policy->dtls_default_mtu(); + + // Sizes are chosen such that small messages share a record and large + // messages span multiple datagrams. The message types are irrelevant. + const auto wire = transmit_server_flight(result, + endpoints, + { + synthetic_message(EncryptedExtensions, epoch, 40), + synthetic_message(CertificateRequest, epoch, 300), + synthetic_message(Certificate, epoch, 1000), + synthetic_message(CertificateVerify, epoch, 25), + synthetic_message(Finished, epoch, 700), + }); + + result.require("flight spans multiple datagrams", wire.size() > 1); + for(const auto& datagram : wire) { + result.test_sz_eq("single-epoch flight has one record per datagram", datagram.records.size(), 1); + } + + for(size_t i = 0; i + 1 < wire.size(); ++i) { + result.test_sz_lt("datagram leaves no room for another fragment", mtu - wire[i].length, min_fragment_size); + } + + result.require("first datagram holds a record", !wire.front().records.empty()); + const auto& first_record = wire.front().records.front(); + result.require("first record is shared by the first three messages", first_record.fragments.size() == 3); + for(uint16_t i = 0; i < 3; ++i) { + result.test_u16_eq("message sequence number", first_record.fragments[i].message_seq, i); + } + }); + }; + + return { + packing_up_to_the_mtu("messages are packed into records and datagrams up to the MTU (unprotected)", + TLS::EpochNumber::unprotected()), + packing_up_to_the_mtu("messages are packed into records and datagrams up to the MTU (protected)", + TLS::EpochNumber::handshake_traffic()), + + CHECK("a message larger than a datagram is fragmented, its first fragment filling up the pending record", + [](Test::Result& result) { + const auto endpoints = make_endpoints(make_policy(500), Keys::HandshakeTraffic); + const size_t mtu = endpoints.policy->dtls_default_mtu(); + + const auto wire = transmit_server_flight( + result, + endpoints, + { + synthetic_message(EncryptedExtensions, TLS::EpochNumber::handshake_traffic(), 50), + synthetic_message(Certificate, TLS::EpochNumber::handshake_traffic(), 2500), + }); + + result.require("large message spans multiple datagrams", wire.size() > 2); + + result.require("first datagram holds one record", wire.front().records.size() == 1); + const auto& first_record = wire.front().records.front(); + result.require("first record holds the small message and the beginning of the large one", + first_record.fragments.size() == 2); + result.test_u16_eq("second fragment is of the large message", first_record.fragments[1].message_seq, 1); + result.test_sz_eq("second fragment is the large message's first", first_record.fragments[1].offset, 0); + result.test_sz_eq("first fragment of the large message fills up the datagram", wire.front().length, mtu); + + for(size_t i = 1; i < wire.size(); ++i) { + result.require("subsequent datagram holds one record", wire[i].records.size() == 1); + result.test_sz_eq( + "subsequent record holds a single fragment", wire[i].records.front().fragments.size(), 1); + if(i + 1 < wire.size()) { + result.test_sz_eq("non-final datagram is filled up to the MTU", wire[i].length, mtu); + } + } + }), + + CHECK("messages of different epochs may share a datagram but never a record", + [](Test::Result& result) { + const auto endpoints = make_endpoints(make_policy(500), Keys::HandshakeTraffic); + + // Epoch purity of the records is checked by transmit_server_flight() + const auto wire = transmit_server_flight( + result, + endpoints, + { + synthetic_message(ServerHello, TLS::EpochNumber::unprotected(), 90), + synthetic_message(EncryptedExtensions, TLS::EpochNumber::handshake_traffic(), 40), + synthetic_message(Certificate, TLS::EpochNumber::handshake_traffic(), 900), + synthetic_message(CertificateVerify, TLS::EpochNumber::handshake_traffic(), 80), + synthetic_message(Finished, TLS::EpochNumber::handshake_traffic(), 32), + }); + + result.require("first datagram holds two records", wire.front().records.size() == 2); + const auto& unprotected_record = wire.front().records[0]; + const auto& protected_record = wire.front().records[1]; + + result.test_is_true("first record is unprotected", unprotected_record.epoch.is_unprotected()); + result.test_sz_eq( + "unprotected record holds the ServerHello only", unprotected_record.fragments.size(), 1); + + result.test_is_true("second record is protected", protected_record.epoch.is_protected()); + result.require("protected record holds fragments", !protected_record.fragments.empty()); + result.test_u16_eq("protected record starts with the EncryptedExtensions", + protected_record.fragments.front().message_seq, + 1); + + for(size_t i = 1; i < wire.size(); ++i) { + for(const auto& record : wire[i].records) { + result.test_is_true("subsequent records are protected", record.epoch.is_handshake_traffic()); + } + } + }), + + CHECK("a dummy ChangeCipherSpec in a flight is rejected without emitting anything", + [](Test::Result& result) { + const auto endpoints = make_endpoints(make_policy(), Keys::HandshakeTraffic); + + // RFC 9147 5 + // DTLS implementations do not use the TLS 1.3 "compatibility mode" [...]. + const std::vector flight = { + synthetic_message(ServerHello, TLS::EpochNumber::unprotected(), 90), + TLS::Flight::Dummy_ChangeCipherSpec{}, + synthetic_message(EncryptedExtensions, TLS::EpochNumber::handshake_traffic(), 40), + }; + + result.test_throws("flight with a dummy CCS is rejected", [&] { + endpoints.server.io->send(flight, TLS::Expected_Response::Flight); + }); + result.test_is_true("nothing was emitted", endpoints.server.callbacks->datagrams().empty()); + }), + + CHECK("sending a flight arms the retransmission timer", + [](Test::Result& result) { + Exchange exchange(result); + exchange.send_server_flight(); + + const auto& delays = exchange.server().callbacks->registered_delays(); + result.require("retransmission and flight timers were registered", delays.size() == 2); + result.test_is_true( + "retransmission timer is registered with the initial timeout", + std::find(delays.begin(), delays.end(), Exchange::initial_timeout_ms) != delays.end()); + }), + }; +} + +/// Tests the server's reaction to incoming ACKs, the retransmission of its flight and its own ACKs +std::vector retransmissions_and_acknowledgements() { + using enum TLS::Handshake_Type; + using enum TLS::Record_Type; + + constexpr size_t initial_timeout_ms = Exchange::initial_timeout_ms; + constexpr size_t ack_timeout_ms = Exchange::ack_timeout_ms; + + // The IO reports the next timeout as optional, while the test + // predicates for optionals compare optional. + const auto next_timeout = [](const Endpoint& endpoint) -> std::optional { + if(const auto timeout = endpoint.io->next_retransmission_timeout()) { + return timeout->count(); + } + return std::nullopt; + }; + + struct Server_Response { + std::vector flight; + std::vector output; + bool retransmission_timer_was_running; + bool flight_guard_was_armed; + }; + + // The server sent a flight and then receives the first fragment of the peer's next flight. + // Returns the flight along with the server's reaction when the retransmission timer ran out. + const auto server_output_after_first_fragment_of_next_flight = [](Test::Result& result, bool committed) { + Exchange exchange(result); + if(committed) { + exchange.commit(); + } + auto flight = exchange.send_server_flight(); + + const auto peer_flight = exchange.client_sends_fragmented_message(); + result.test_is_true("fragment yields no event", exchange.deliver_to_server(peer_flight.front()).events.empty()); + + const size_t rescheduled_operations = exchange.advance_server_clock(initial_timeout_ms); + return Server_Response{ + .flight = std::move(flight), + .output = exchange.take_server_output(), + .retransmission_timer_was_running = rescheduled_operations > 0, + .flight_guard_was_armed = exchange.server().io->next_retransmission_timeout().has_value(), + }; + }; + + return { + CHECK("the retransmission timer re-sends the whole flight with new record numbers", + [](Test::Result& result) { + Exchange exchange(result); + const auto original = exchange.send_server_flight(); + + exchange.advance_server_clock(initial_timeout_ms - 1); + result.test_is_true("nothing is re-sent before the timeout", exchange.take_server_output().empty()); + + exchange.advance_server_clock(1); + const auto retransmitted = exchange.take_server_output(); + result.test_is_true("handshake bytes are identical", + fragments_of(retransmitted) == fragments_of(original)); + + // The records are re-packed. Given that they are the same as before, the datagrams come out the same. + result.require("flight is packed into the same number of datagrams", + retransmitted.size() == original.size()); + + // RFC 9147 5.8.1: Retransmissions are new records, i.e. they use new record numbers + const auto original_numbers = record_numbers(original); + for(const auto& number : record_numbers(retransmitted)) { + const bool is_new = std::ranges::all_of(original_numbers, [&](const auto& original_number) { + return original_number.epoch != number.epoch || + original_number.sequence_number < number.sequence_number; + }); + result.test_is_true("record number is higher than any previous one in its epoch", is_new); + } + }), + + CHECK("a protected ACK covering all outstanding records cancels the retransmission timer", + [](Test::Result& result) { + Exchange exchange(result); + exchange.commit(); + const auto flight = exchange.send_server_flight(); + + exchange.client_acknowledges(record_numbers(flight)); + + result.test_is_true("ACK does not cause output", exchange.take_server_output().empty()); + result.test_sz_eq( + "retransmission timer is cancelled", exchange.advance_server_clock(initial_timeout_ms), 0); + result.test_is_true("flight is not re-sent", exchange.take_server_output().empty()); + result.test_is_true("the flight guard remains armed while waiting for the peer's response flight", + exchange.server().io->next_retransmission_timeout().has_value()); + + // When the awaited flight completes, the interaction is over and the guard is disarmed + exchange.deliver_to_server(exchange.client_sends(Finished, 32).front()); + exchange.server().io->notify_received_complete_flight(TLS::Expected_Response::None); + result.test_is_false("the flight guard is cancelled when the interaction succeeded", + exchange.server().io->next_retransmission_timeout().has_value()); + }), + + CHECK("an ACK covering some records leaves the remaining ones to be retransmitted", + [](Test::Result& result) { + Exchange exchange(result); + exchange.commit(); + const auto flight = exchange.send_server_flight(); + result.require("first datagram holds multiple records", flight.front().records.size() >= 2); + + // The first record holds the ServerHello only + const std::vector acknowledged = {flight.front().records.front().number()}; + exchange.client_acknowledges(acknowledged); + result.test_is_true("a partial ACK does not cause an immediate retransmission", + exchange.take_server_output().empty()); + + exchange.advance_server_clock(initial_timeout_ms); + const auto retransmitted = exchange.take_server_output(); + const auto retransmitted_fragments = fragments_of(retransmitted); + result.test_is_true("only the unacknowledged fragments are re-sent", + retransmitted_fragments == fragments_of(flight, acknowledged)); + for(const auto& fragment : retransmitted_fragments) { + result.test_is_true("acknowledged ServerHello is not re-sent", fragment.message_seq != 0); + } + + // Acknowledging any transmission of a record is sufficient + exchange.client_acknowledges(record_numbers(retransmitted)); + result.test_sz_eq( + "retransmission timer is cancelled", exchange.advance_server_clock(2 * initial_timeout_ms), 0); + result.test_is_true("acknowledging the retransmission cancels the timer", + exchange.take_server_output().empty()); + }), + + CHECK("the first fragment of the peer's next flight implicitly acknowledges the flight", + [=](Test::Result& result) { + // RFC 9147 7 + // In particular, receiving a message from a handshake flight implicitly + // acknowledges all messages from the previous flight(s). + const auto response = server_output_after_first_fragment_of_next_flight(result, true); + result.test_sz_eq("flight is not re-sent", count_records(response.output, Handshake), 0); + result.test_is_false("retransmission timer is cancelled", response.retransmission_timer_was_running); + result.test_is_true("the flight guard stays armed after the implicit acknowledgement", + response.flight_guard_was_armed); + }), + + CHECK( + "a duplicate of a previous message is not an implicit ACK", + [](Test::Result& result) { + Exchange exchange(result); + exchange.commit(); + exchange.send_server_flight(); + + // The peer's Finished completes the first flight, ... + const auto finished = exchange.client_sends(Finished, 32); + result.require("peer sends a single datagram", finished.size() == 1); + result.test_sz_eq("Finished is delivered", exchange.deliver_to_server(finished.front()).events.size(), 1); + + // ... which concludes the interaction: the server acknowledges the peer's final flight + exchange.server().io->notify_received_complete_flight(TLS::Expected_Response::None); + result.test_is_true("the final flight is acknowledged immediately", + count_records(exchange.take_server_output(), ACK) == 1); + + // ... the server answers with another flight, ... + const auto second_flight = exchange.send_server_flight( + {synthetic_message(Finished, TLS::EpochNumber::handshake_traffic(), 32)}, TLS::Expected_Response::None); + + // ... and the peer retransmits its Finished, because it has not heard from the server yet. + const auto duplicate = exchange.client_retransmits(); + result.require("peer retransmits a single datagram", duplicate.size() == 1); + const auto duplicate_numbers = record_numbers(exchange.decode_client_datagrams(duplicate)); + result.test_is_true("duplicate yields no event", + exchange.deliver_to_server(duplicate.front()).events.empty()); + + // The duplicate is acknowledged but the second flight remains unacknowledged + exchange.advance_server_clock(ack_timeout_ms); + result.test_is_true("duplicate is acknowledged", + contains(acknowledged_by(exchange.take_server_output()), duplicate_numbers.front())); + + exchange.advance_server_clock(initial_timeout_ms - ack_timeout_ms); + result.test_is_true("second flight is re-sent", + fragments_of(exchange.take_server_output()) == fragments_of(second_flight)); + }), + + CHECK("a fragment beyond the buffering window is no implicit ACK and not acknowledged", + [](Test::Result& result) { + Exchange exchange(result); + exchange.commit(); + const auto flight = exchange.send_server_flight(); + + // The server hasn't seen the peer's first message yet. The message sequence number of the next + // fragment is further ahead than the server is willing to buffer. It is not delivered. + const size_t skipped_messages = TLS::DTLS_Handshake_Layer::MAX_BUFFERED_FUTURE_MESSAGES + 1; + for(size_t i = 0; i < skipped_messages; ++i) { + exchange.client_sends(Certificate, 5); + } + const auto fragment = exchange.client_sends(Certificate, 5); + result.require("peer sends a single datagram", fragment.size() == 1); + result.test_is_true("fragment yields no event", + exchange.deliver_to_server(fragment.front()).events.empty()); + + exchange.advance_server_clock(initial_timeout_ms); + const auto output = exchange.take_server_output(); + result.test_is_true("flight is re-sent in full", fragments_of(output) == fragments_of(flight)); + result.test_sz_eq("fragment is not acknowledged", count_records(output, ACK), 0); + }), + + CHECK("after a partial flight, the ACK timer emits an ACK for the received records", + [](Test::Result& result) { + Exchange exchange(result); + exchange.commit(); + + const auto peer_flight = exchange.client_sends_fragmented_message(); + const auto peer_records = record_numbers(exchange.decode_client_datagrams(peer_flight)); + + exchange.deliver_to_server(peer_flight[0]); + exchange.advance_server_clock(ack_timeout_ms / 2); + exchange.deliver_to_server(peer_flight[1]); + exchange.advance_server_clock(ack_timeout_ms / 2 - 1); + result.test_is_true("no ACK before the ACK timeout", exchange.take_server_output().empty()); + + exchange.advance_server_clock(1); + const auto output = exchange.take_server_output(); + result.test_sz_eq("one ACK record is sent", count_records(output, ACK), 1); + result.test_is_true("ACK lists the received records", + acknowledged_by(output) == std::vector({peer_records[0], peer_records[1]})); + + exchange.advance_server_clock(initial_timeout_ms); + result.test_is_true("the ACK is sent once", exchange.take_server_output().empty()); + }), + + CHECK("no ACKs are sent as long as the protocol version is not committed", + [](Test::Result& result) { + Exchange exchange(result); + exchange.deliver_to_server(exchange.client_sends_fragmented_message().front()); + + exchange.advance_server_clock(initial_timeout_ms); + result.test_is_true("no ACK is sent", exchange.take_server_output().empty()); + }), + + CHECK("responding to a completed flight cancels the ACK timer", + [&](Test::Result& result) { + Exchange exchange(result); + exchange.commit(); + exchange.send_server_flight(); + + const auto finished = exchange.client_sends(Finished, 32); + result.require("peer sends a single datagram", finished.size() == 1); + result.test_sz_eq( + "Finished is delivered", exchange.deliver_to_server(finished.front()).events.size(), 1); + + // The peer's flight is complete and the server responds with a + // flight of its own, implicitly acknowledging the peer's flight. + exchange.server().io->notify_received_complete_flight(TLS::Expected_Response::Flight); + const auto flight = exchange.send_server_flight(); + + result.test_opt_u64_eq("the response flight armed the retransmission timer, not the ACK timer", + next_timeout(exchange.server()), + initial_timeout_ms); + + exchange.advance_server_clock(ack_timeout_ms); + result.test_is_true("no ACK is sent", exchange.take_server_output().empty()); + + exchange.advance_server_clock(initial_timeout_ms - ack_timeout_ms); + result.test_is_true("the retransmission timer is not affected", + fragments_of(exchange.take_server_output()) == fragments_of(flight)); + }), + + CHECK("a complete flight makes pending ACKs obsolete", + [&](Test::Result& result) { + Exchange exchange(result); + exchange.commit(); + exchange.send_server_flight(); + exchange.deliver_to_server(exchange.client_sends_fragmented_message().front()); + + // The channel received the final message of the peer's flight and is about to respond + exchange.server().io->notify_received_complete_flight(TLS::Expected_Response::Flight); + + // The implicit ACK by our response flight will conclude the + // interaction, so the ACK timer is cancelled. The retransmission + // timer was already stopped when the peer's flight progressed. + result.test_opt_is_null("no timer remains armed", next_timeout(exchange.server())); + + exchange.advance_server_clock(ack_timeout_ms); + result.test_is_true("ACK timer does not emit an ACK", exchange.take_server_output().empty()); + + exchange.send_server_flight(); + exchange.server().io->notify_received_complete_flight(TLS::Expected_Response::None); + result.test_is_true("there is nothing left to acknowledge", exchange.take_server_output().empty()); + }), + + CHECK("the final flight is acknowledged immediately", + [](Test::Result& result) { + Exchange exchange(result); + exchange.commit(); + exchange.send_server_flight(); + + const auto finished = exchange.client_sends(Finished, 32); + result.require("peer sends a single datagram", finished.size() == 1); + const auto finished_numbers = record_numbers(exchange.decode_client_datagrams(finished)); + result.test_sz_eq( + "Finished is delivered", exchange.deliver_to_server(finished.front()).events.size(), 1); + result.test_is_true("Finished is not acknowledged right away", exchange.take_server_output().empty()); + + // There is no response to the peer's last flight that could implicitly acknowledge it. + exchange.server().io->notify_received_complete_flight(TLS::Expected_Response::None); + const auto output = exchange.take_server_output(); + result.test_sz_eq("one ACK record is sent", count_records(output, ACK), 1); + result.test_is_true("ACK lists the peer's Finished", acknowledged_by(output) == finished_numbers); + }), + + CHECK( + "the final flight's ACK is not repeated by the ACK timer but retained for retransmissions", + [](Test::Result& result) { + Exchange exchange(result); + exchange.commit(); + exchange.send_server_flight(); + + const auto finished = exchange.client_sends(Finished, 32); + result.require("peer sends a single datagram", finished.size() == 1); + const auto original_numbers = record_numbers(exchange.decode_client_datagrams(finished)); + result.require("peer sends a single record", original_numbers.size() == 1); + result.test_sz_eq("Finished is delivered", exchange.deliver_to_server(finished.front()).events.size(), 1); + + exchange.server().io->notify_received_complete_flight(TLS::Expected_Response::None); + result.test_sz_eq("the final flight is acknowledged", count_records(exchange.take_server_output(), ACK), 1); + + exchange.advance_server_clock(ack_timeout_ms); + result.test_is_true("ACK timer does not repeat the ACK", exchange.take_server_output().empty()); + + // The peer never saw the ACK and retransmits its Finished in a new record + exchange.client().callbacks->advance_clock(initial_timeout_ms); + const auto retransmission = exchange.client().callbacks->take_datagrams(); + result.require("peer retransmits a single datagram", retransmission.size() == 1); + const auto retransmitted_numbers = record_numbers(exchange.decode_client_datagrams(retransmission)); + result.require("peer retransmits a single record", retransmitted_numbers.size() == 1); + result.test_is_true("retransmission is not processed again", + exchange.deliver_to_server(retransmission.front()).events.empty()); + + exchange.advance_server_clock(ack_timeout_ms); + const auto output = exchange.take_server_output(); + result.test_sz_eq("one ACK record is sent", count_records(output, ACK), 1); + result.test_is_true("ACK covers the original record", + contains(acknowledged_by(output), original_numbers.front())); + result.test_is_true("ACK covers the retransmitted record", + contains(acknowledged_by(output), retransmitted_numbers.front())); + }), + + CHECK("closing for writing or shutting down cancels the retransmission and ACK timers", + [](Test::Result& result) { + // Closing the write side (close_notify sent) is sufficient, a full shutdown includes it + const std::vector>> closures = { + {"closed for writing", [](TLS::Channel_IO& io) { io.notify_closed_for_writing(); }}, + {"shutdown", [](TLS::Channel_IO& io) { io.notify_shutdown(); }}, + }; + + for(const auto& [name, close] : closures) { + { + Exchange exchange(result); + exchange.commit(); + exchange.send_server_flight(); + + close(*exchange.server().io); + + result.test_sz_eq("retransmission timer is cancelled (" + name + ")", + exchange.advance_server_clock(10 * initial_timeout_ms), + 0); + result.test_is_true("flight is not re-sent (" + name + ")", exchange.take_server_output().empty()); + } + + { + Exchange exchange(result); + exchange.commit(); + exchange.deliver_to_server(exchange.client_sends_fragmented_message().front()); + + close(*exchange.server().io); + + exchange.advance_server_clock(10 * initial_timeout_ms); + result.test_is_true("ACK timer is cancelled, no ACK is sent (" + name + ")", + exchange.take_server_output().empty()); + } + } + }), + + CHECK( + "the handshake epoch is retained for twice the maximum segment lifetime", + [=](Test::Result& result) { + // RFC 9293 3.4.1: Maximum Segment Lifetime of 2 minutes + constexpr uint64_t msl_ms = 2 * 60 * 1000; + + Exchange exchange(result); + exchange.commit(); + exchange.send_server_flight(); + + // The peer's Finished is the last message of the handshake, the server acknowledges it + const auto finished = exchange.client_sends(Finished, 32); + result.require("peer sends a single datagram", finished.size() == 1); + result.test_sz_eq("Finished is delivered", exchange.deliver_to_server(finished.front()).events.size(), 1); + exchange.server().io->notify_received_complete_flight(TLS::Expected_Response::None); + exchange.advance_server_clock(ack_timeout_ms); + exchange.take_server_output(); + + // The peer never sees that ACK and retransmits its Finished (protected with the handshake keys) + // several times. These are sent now but only delivered to the server later on. + const auto retransmission = [&](uint64_t delay_ms) { + exchange.client().callbacks->advance_clock(delay_ms); + const auto datagrams = exchange.client().callbacks->take_datagrams(); + result.require("peer retransmits a single datagram", datagrams.size() == 1); + const auto numbers = record_numbers(exchange.decode_client_datagrams(datagrams)); + result.require("peer retransmits a single record", numbers.size() == 1); + return std::pair{datagrams.front(), numbers.front()}; + }; + const auto [retransmission_1, number_1] = retransmission(initial_timeout_ms); + const auto [retransmission_2, number_2] = retransmission(2 * initial_timeout_ms); + const auto [retransmission_3, number_3] = retransmission(4 * initial_timeout_ms); + + // The handshake completes on both sides: the application epoch is now available + const std::vector transcript_hash(32, 0x00); + for(const auto* endpoint : {&exchange.client(), &exchange.server()}) { + endpoint->cipher_state->advance_with_server_finished(transcript_hash); + endpoint->cipher_state->advance_with_client_finished(transcript_hash); + } + result.test_is_true("server reads the application epoch", + exchange.server_read_epoch().application_traffic_index() == 0); + + // The peer's first record in the application epoch. The handshake epoch is kept for a little longer. + const auto& delays = exchange.server().callbacks->registered_delays(); + const size_t registered_before = delays.size(); + const auto application_data = exchange.client_sends_application_data(); + result.require("peer sends a single datagram", application_data.size() == 1); + const auto events = exchange.deliver_to_server(application_data.front()).events; + result.test_is_true("application data is delivered", + events.size() == 1 && std::holds_alternative(events[0])); + result.test_is_true("a timer for twice the maximum segment lifetime is registered", + delays.size() > registered_before && delays.back() == 2 * msl_ms); + + // Delivers a retransmitted Finished and tells whether the server could deprotect and acknowledge it + const auto acknowledged = [&](const std::vector& datagram, const TLS::RecordNumber& number) { + result.test_is_true("retransmission yields no event", + exchange.deliver_to_server(datagram).events.empty()); + exchange.advance_server_clock(ack_timeout_ms); + return contains(acknowledged_by(exchange.take_server_output()), number); + }; + + // One maximum segment lifetime would be sufficient for a regular epoch change + exchange.advance_server_clock(msl_ms); + result.test_is_true("handshake epoch is readable after one maximum segment lifetime", + acknowledged(retransmission_1, number_1)); + + exchange.advance_server_clock(msl_ms - ack_timeout_ms - 1); + result.test_is_true("handshake epoch is readable until the timer expires", + acknowledged(retransmission_2, number_2)); + + // The timer expired in the meantime + result.test_is_false("handshake epoch is discarded when the timer expires", + acknowledged(retransmission_3, number_3)); + }), + }; +} + +/// Tests KeyUpdates in both directions (RFC 9147 8.) +std::vector key_updates() { + using enum TLS::Handshake_Type; + using enum TLS::Record_Type; + + constexpr auto old_epoch = epoch_appdata_0; + constexpr auto new_epoch = epoch_appdata_1; + constexpr size_t initial_timeout_ms = Exchange::initial_timeout_ms; + constexpr size_t ack_timeout_ms = Exchange::ack_timeout_ms; + + // RFC 9293 3.4.1: Maximum Segment Lifetime of 2 minutes, see RFC 9147 4.2.1 + constexpr uint64_t msl_ms = 2 * 60 * 1000; + + const auto single_record = [](Test::Result& result, const std::vector& wire) -> const auto& { + result.require("a single datagram holding a single record was sent", + wire.size() == 1 && wire.front().records.size() == 1); + return wire.front().records.front(); + }; + + const auto expect_key_update = [=](Test::Result& result, + const std::vector& wire, + TLS::EpochNumber epoch, + bool update_requested) { + const auto& record = single_record(result, wire); + result.test_enum_eq("record is a handshake record", record.type, Handshake); + result.test_is_true("record is protected with the current epoch", record.epoch == epoch); + result.require("record holds a single fragment", record.fragments.size() == 1); + result.test_enum_eq("fragment is a KeyUpdate", record.fragments.front().type, KeyUpdate); + result.test_bin_eq( + "update_requested", record.fragments.front().bytes, std::vector(1, update_requested ? 1 : 0)); + }; + + const auto expect_application_data = + [=](Test::Result& result, const std::vector& wire, TLS::EpochNumber epoch) { + const auto& record = single_record(result, wire); + result.test_enum_eq("record is an application data record", record.type, ApplicationData); + result.test_is_true("record is protected with the expected epoch", record.epoch == epoch); + }; + + const auto delivers_application_data = [](Exchange& exchange, const std::vector& datagram) { + const auto events = exchange.deliver_to_server(datagram).events; + return events.size() == 1 && std::holds_alternative(events.front()); + }; + + // The server sends a (post-handshake) message ahead of its KeyUpdate. The + // message is not part of the KeyUpdate, which allows ACKing one without the other. + const auto send_other_post_handshake_message = [&](Exchange& exchange) { + return exchange.send_server_flight({synthetic_message(NewSessionTicket, old_epoch, 30)}, + TLS::Expected_Response::None); + }; + + // The server receives a KeyUpdate and the application subsequently sends data + const auto server_sends_data_after_key_update = [=](Test::Result& result, bool update_requested) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + exchange.server_receives_key_update(update_requested); + result.test_is_true("nothing is sent right away", exchange.take_server_output().empty()); + + auto wire = exchange.send_server_application_data(); + + // RFC 9147 8. Reciprocation is a KeyUpdate that has to be acknowledged as any other. + result.test_is_true("post-handshake messages are blocked while a reciprocating KeyUpdate is pending", + exchange.server().io->can_send_post_handshake_messages() != update_requested); + return wire; + }; + + return { + CHECK("a KeyUpdate is sent under the current epoch and blocks post-handshake messages until acknowledged", + [=](Test::Result& result) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + result.require("post-handshake messages are allowed", + exchange.server().io->can_send_post_handshake_messages()); + + exchange.server().io->update_traffic_keys(false); + + expect_key_update(result, exchange.take_server_output(), old_epoch, false); + result.test_is_false("post-handshake messages are blocked", + exchange.server().io->can_send_post_handshake_messages()); + + // RFC 9147 8. + // [...] implementations MUST NOT send records with the new keys [...] until the previous + // KeyUpdate has been acknowledged [...]. + result.test_is_true("write epoch is not advanced", exchange.server_write_epoch() == old_epoch); + expect_application_data(result, exchange.send_server_application_data(), old_epoch); + }), + + CHECK("the ACK of the KeyUpdate record switches to the new write keys", + [=](Test::Result& result) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + exchange.server().io->update_traffic_keys(false); + const auto key_update = exchange.take_server_output(); + + exchange.client_acknowledges(record_numbers(key_update)); + + // The KeyUpdate exchange is over: nothing is left to wait for, so + // the flight guard is disarmed along with the retransmission timer. + result.test_is_false("the flight guard is disarmed when the KeyUpdate is acknowledged", + exchange.server().io->next_retransmission_timeout().has_value()); + + result.test_is_true("write epoch is advanced", exchange.server_write_epoch() == new_epoch); + result.test_is_true("post-handshake messages are allowed again", + exchange.server().io->can_send_post_handshake_messages()); + + exchange.peer_reads_with_updated_keys(); + expect_application_data(result, exchange.send_server_application_data(), new_epoch); + + result.test_sz_eq( + "retransmission timer is cancelled", exchange.advance_server_clock(2 * initial_timeout_ms), 0); + }), + + CHECK("an ACK that does not cover the KeyUpdate record does not advance the write keys", + [=](Test::Result& result) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + const auto other_message = send_other_post_handshake_message(exchange); + exchange.server().io->update_traffic_keys(false); + const auto key_update = exchange.take_server_output(); + + exchange.client_acknowledges(record_numbers(other_message)); + + result.test_is_true("write epoch is not advanced", exchange.server_write_epoch() == old_epoch); + result.test_is_false("post-handshake messages are still blocked", + exchange.server().io->can_send_post_handshake_messages()); + expect_application_data(result, exchange.send_server_application_data(), old_epoch); + + // The KeyUpdate is retransmitted on its own + exchange.advance_server_clock(initial_timeout_ms); + result.test_is_true("only the KeyUpdate is re-sent", + fragments_of(exchange.take_server_output()) == fragments_of(key_update)); + }), + + CHECK("an unacknowledged KeyUpdate is retransmitted under the old epoch", + [=](Test::Result& result) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + exchange.server().io->update_traffic_keys(false); + + const auto& delays = exchange.server().callbacks->registered_delays(); + result.require("retransmission and flight timers were registered", delays.size() == 2); + result.test_is_true("retransmission timer is armed with the initial timeout", + std::find(delays.begin(), delays.end(), initial_timeout_ms) != delays.end()); + + const auto original = exchange.take_server_output(); + exchange.advance_server_clock(initial_timeout_ms - 1); + result.test_is_true("nothing is re-sent before the timeout", exchange.take_server_output().empty()); + + exchange.advance_server_clock(1); + const auto retransmitted = exchange.take_server_output(); + expect_key_update(result, retransmitted, old_epoch, false); + result.test_is_true("handshake bytes are identical", + fragments_of(retransmitted) == fragments_of(original)); + result.test_is_false("the retransmission is a new record", + contains(record_numbers(original), record_numbers(retransmitted).front())); + + result.test_is_true("write epoch is not advanced", exchange.server_write_epoch() == old_epoch); + result.test_is_false("post-handshake messages are still blocked", + exchange.server().io->can_send_post_handshake_messages()); + + // Acknowledging the retransmission is as good as acknowledging the original + exchange.client_acknowledges(record_numbers(retransmitted)); + result.test_is_true("write epoch is advanced", exchange.server_write_epoch() == new_epoch); + }), + + CHECK("old write epochs are discarded once no unacknowledged records remain", + [=](Test::Result& result) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + const auto other_message = send_other_post_handshake_message(exchange); + exchange.server().io->update_traffic_keys(false); + const auto key_update = exchange.take_server_output(); + + exchange.client_acknowledges(record_numbers(key_update)); + result.test_is_true("write epoch is advanced", exchange.server_write_epoch() == new_epoch); + result.test_is_true("old epoch is kept as long as it holds unacknowledged records", + exchange.server_can_write_epoch(old_epoch)); + + // Those records are still retransmitted under the epoch they were sent in + exchange.advance_server_clock(initial_timeout_ms); + const auto retransmitted = exchange.take_server_output(); + result.test_is_true("the other message is re-sent", + fragments_of(retransmitted) == fragments_of(other_message)); + for(const auto& datagram : retransmitted) { + for(const auto& record : datagram.records) { + result.test_is_true("record is protected with the old epoch", record.epoch == old_epoch); + } + } + + exchange.client_acknowledges(record_numbers(retransmitted)); + result.test_is_false("old epoch is discarded", exchange.server_can_write_epoch(old_epoch)); + result.test_is_true("new epoch is retained", exchange.server_can_write_epoch(new_epoch)); + }), + + CHECK("a received KeyUpdate advances the read keys and is acknowledged", + [=](Test::Result& result) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + + const auto key_update_record = exchange.server_receives_key_update(false); + + result.test_is_true("read epoch is advanced", exchange.server_read_epoch() == new_epoch); + result.test_is_true("write epoch is not advanced", exchange.server_write_epoch() == old_epoch); + result.test_is_true("no immediate response", exchange.take_server_output().empty()); + + // KeyUpdates must be acknowledged (RFC 9147 8.), by the same means as other handshake messages + exchange.advance_server_clock(ack_timeout_ms); + const auto output = exchange.take_server_output(); + result.test_sz_eq("one ACK record is sent", count_records(output, ACK), 1); + result.test_is_true("ACK lists the KeyUpdate record", + acknowledged_by(output) == std::vector{key_update_record}); + }), + + CHECK("a post-handshake flight does not drop the ACK for the peer's KeyUpdate", + [=](Test::Result& result) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + + const auto key_update_record = exchange.server_receives_key_update(false); + + // The server sends a post-handshake message of its own while the + // ACK for the peer's KeyUpdate is still pending. + exchange.send_server_flight({synthetic_message(NewSessionTicket, old_epoch, 30)}, + TLS::Expected_Response::None); + + exchange.advance_server_clock(ack_timeout_ms); + const auto output = exchange.take_server_output(); + result.test_sz_eq("one ACK record is sent", count_records(output, ACK), 1); + result.test_is_true("ACK lists the peer's KeyUpdate record", + contains(acknowledged_by(output), key_update_record)); + }), + + CHECK("a received KeyUpdate is not reciprocated unless requested", + [=](Test::Result& result) { + expect_application_data(result, server_sends_data_after_key_update(result, false), old_epoch); + }), + + CHECK("a requested KeyUpdate is reciprocated before the next application data is sent", + [=](Test::Result& result) { + const auto wire = server_sends_data_after_key_update(result, true); + result.require("KeyUpdate and application data are sent in separate datagrams", wire.size() == 2); + + // RFC 9846 4.7.3: [...] MUST send a KeyUpdate of its own with request_update set to + // "update_not_requested" prior to sending its next Application Data record. + expect_key_update(result, {wire[0]}, old_epoch, false); + expect_application_data(result, {wire[1]}, old_epoch); + }), + + CHECK( + "the previous read epoch is discarded two minutes after the peer started using the new keys", + [=](Test::Result& result) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + exchange.server_receives_key_update(false); + + // The peer continues with the old keys until it learns that the KeyUpdate was acknowledged. + // These records are protected now but delivered later on. + const auto old_epoch_before_any_expiry = exchange.client_sends_application_data().front(); + const auto old_epoch_before_expiry = exchange.client_sends_application_data().front(); + const auto old_epoch_after_expiry = exchange.client_sends_application_data().front(); + + // RFC 9147 8. + // [...] receivers MUST retain the pre-update keying material until receipt and + // successful decryption of a message using the new keys. + exchange.advance_server_clock(10 * msl_ms); + result.test_is_true("previous epoch is retained as long as the peer does not use the new keys", + delivers_application_data(exchange, old_epoch_before_any_expiry)); + + // The peer learned that the KeyUpdate was acknowledged and starts using the new keys + const auto& delays = exchange.server().callbacks->registered_delays(); + const size_t registered_before = delays.size(); + exchange.peer_writes_with_updated_keys(); + result.test_is_true("new epoch is readable", + delivers_application_data(exchange, exchange.client_sends_application_data().front())); + result.test_is_true("a timer for the maximum segment lifetime is registered", + delays.size() > registered_before && delays.back() == msl_ms); + + exchange.advance_server_clock(msl_ms - 1); + result.test_is_true("previous epoch is readable until the timer expires", + delivers_application_data(exchange, old_epoch_before_expiry)); + + exchange.advance_server_clock(1); + result.test_is_false("previous epoch is discarded when the timer expires", + delivers_application_data(exchange, old_epoch_after_expiry)); + + result.test_is_true("latest epoch is retained", + delivers_application_data(exchange, exchange.client_sends_application_data().front())); + }), + + CHECK("a post-handshake message under an outdated read epoch is rejected", + [=](Test::Result& result) { + Exchange exchange(result, Keys::ApplicationTraffic); + exchange.commit(); + exchange.server_receives_key_update(false); + + // The peer did not receive the ACK yet and still sends under the old epoch + const auto message = exchange.client_sends(NewSessionTicket, 20, old_epoch); + result.require("peer sends a single datagram", message.size() == 1); + + result.test_throws("message is rejected", + "Received a new post-handshake message under an outdated epoch", + [&] { exchange.deliver_to_server(message.front()); }); + }), + + CHECK("a KeyUpdate is requested before the deprotection failure limit is reached", + [=](Test::Result& result) { + // RFC 9147 4.5.3 + // Implementations SHOULD initiate a key update with update_requested before reaching + // [the deprotection failure limit]. + constexpr size_t failure_limit = 4; + Exchange exchange(result, Keys::ApplicationTraffic, failure_limit); + exchange.commit(); + + exchange.server_receives_tampered_records(failure_limit - 1); + result.test_u64_eq("failures are counted", + exchange.server().cipher_state->current_read_epoch_deprotection_failures(), + failure_limit - 1); + + const auto wire = exchange.send_server_application_data(); + result.require("KeyUpdate and application data are sent in separate datagrams", wire.size() == 2); + expect_key_update(result, {wire[0]}, old_epoch, true); + expect_application_data(result, {wire[1]}, old_epoch); + }), + + CHECK( + "a deprotection failure limit of zero or one does not provoke KeyUpdates", + [=](Test::Result& result) { + for(const size_t failure_limit : {0, 1}) { + Exchange exchange(result, Keys::ApplicationTraffic, failure_limit); + exchange.commit(); + + expect_application_data(result, exchange.send_server_application_data(), old_epoch); + + if(failure_limit == 1) { + result.test_no_throw("first deprotection failure does not exceed the limit", + [&] { exchange.server_receives_tampered_records(1); }); + } + result.test_throws("deprotection failures exceeding the limit close the connection", + "Too many deprotection failures in current read epoch", + [&] { exchange.server_receives_tampered_records(1); }); + + result.test_is_true("no KeyUpdate was triggered before closing", exchange.take_server_output().empty()); + } + }), + }; +} + +/// Tests the application data send path, in particular the application's +/// contract to only send data that fits within the negotiated limits (MTU and +/// record size limit from RFC 8449). +std::vector send_application_data() { + using enum TLS::Handshake_Type; + + return { + CHECK("application data at the record payload limit (MTU) is emitted as a single record", + [](Test::Result& result) { + const auto endpoints = make_endpoints(make_policy(400), Keys::ApplicationTraffic); + + // The record payload limit is derived from the MTU when no record size + // limit was negotiated. + TLS::DTLS_Record_Layer rl{*endpoints.policy}; + const size_t record_payload_limit = + rl.record_payload_size_limit(*endpoints.policy, endpoints.client.cipher_state.get()); + + std::vector payload(record_payload_limit); + for(size_t i = 0; i < payload.size(); ++i) { + payload[i] = static_cast(i % 251); + } + + endpoints.client.io->send(payload); + const auto wire = decode_datagrams( + result, endpoints.client.callbacks->take_datagrams(), endpoints.server.cipher_state.get()); + + result.require("single datagram was emitted", wire.size() == 1); + result.require("datagram holds a single record", wire.front().records.size() == 1); + const auto& record = wire.front().records.front(); + result.test_enum_eq( + "record is an application data record", record.type, TLS::Record_Type::ApplicationData); + result.test_is_true("record is protected with the application traffic epoch", + record.epoch.is_application_traffic()); + result.test_sz_eq( + "record payload is at the record payload limit", record.payload_length, record_payload_limit); + result.test_bin_eq("record payload matches the input", record.payload, payload); + }), + + CHECK("application data within a small negotiated record size limit is emitted as a single record", + [](Test::Result& result) { + const auto endpoints = make_endpoints(make_policy(400), Keys::ApplicationTraffic); + + // RFC 8449 4. + // When the "record_size_limit" extension is negotiated, an + // endpoint MUST NOT generate a protected record with plaintext + // that is larger than the RecordSizeLimit value it receives + // from its peer. + // + // The (simulated) peer advertised the minimum legal limit of 64, + // which leaves 63 bytes of payload per protected record. The + // application is expected to adhere to that limit. + endpoints.client.io->set_record_size_limits(64, TLS::MAX_PLAINTEXT_SIZE + 1); + + const std::vector payload(63, 0x42); + + endpoints.client.io->send(payload); + const auto wire = decode_datagrams( + result, endpoints.client.callbacks->take_datagrams(), endpoints.server.cipher_state.get()); + + result.require("single datagram was emitted", wire.size() == 1); + result.require("datagram holds a single record", wire.front().records.size() == 1); + const auto& record = wire.front().records.front(); + result.test_enum_eq( + "record is an application data record", record.type, TLS::Record_Type::ApplicationData); + result.test_sz_eq("record payload is at the negotiated limit", record.payload_length, 63); + result.test_bin_eq("record payload matches the input", record.payload, payload); + }), + + CHECK("oversized application data is rejected", + [](Test::Result& result) { + const auto endpoints = make_endpoints(make_policy(400), Keys::ApplicationTraffic); + + // Without a negotiated record size limit, the protocol's maximum + // plaintext size (plus the content type byte) is the applicable limit. + // The payload below exceeds it. + result.test_throws( + "application data beyond the protocol maximum is rejected", [&] { + const std::vector oversized_payload(20'000, 0x42); + endpoints.client.io->send(oversized_payload); + }); + result.test_is_true("nothing was emitted", endpoints.client.callbacks->datagrams().empty()); + + // With a negotiated record size limit, the payload must fit within it. + endpoints.client.io->set_record_size_limits(64, TLS::MAX_PLAINTEXT_SIZE + 1); + result.test_throws( + "application data beyond the negotiated record size limit is rejected", [&] { + const std::vector oversized_payload(64, 0x42); + endpoints.client.io->send(oversized_payload); + }); + result.test_is_true("nothing was emitted", endpoints.client.callbacks->datagrams().empty()); + }), + + CHECK("a large handshake message is fragmented to fit a small negotiated record size limit", + [](Test::Result& result) { + const auto endpoints = make_endpoints(make_policy(400), Keys::HandshakeTraffic); + + // The (simulated) peer advertised the minimum legal limit of 64. + endpoints.server.io->set_record_size_limits(64, TLS::MAX_PLAINTEXT_SIZE + 1); + + // Certificate is by far the largest message of a typical server + // flight; with a 64-byte limit it must be fragmented into many + // records of at most 63 payload bytes each. + const auto wire = transmit_server_flight( + result, + endpoints, + { + synthetic_message(EncryptedExtensions, TLS::EpochNumber::handshake_traffic(), 40), + synthetic_message(Certificate, TLS::EpochNumber::handshake_traffic(), 900), + synthetic_message(CertificateVerify, TLS::EpochNumber::handshake_traffic(), 80), + synthetic_message(Finished, TLS::EpochNumber::handshake_traffic(), 32), + }); + + for(const auto& datagram : wire) { + for(const auto& record : datagram.records) { + result.test_sz_lte( + "handshake record honors the negotiated record size limit", record.payload_length, 63); + } + } + }), + }; +} + +} // namespace + +BOTAN_REGISTER_TEST_FN("tls", + "tls_channel_io_dtls", + send_flights, + retransmissions_and_acknowledgements, + key_updates, + send_application_data); + +} // namespace Botan_Tests + +#endif diff --git a/src/tests/test_tls_dtls13_cipher_state.cpp b/src/tests/test_tls_dtls13_cipher_state.cpp new file mode 100644 index 00000000000..0c9b7c35d07 --- /dev/null +++ b/src/tests/test_tls_dtls13_cipher_state.cpp @@ -0,0 +1,687 @@ +/* +* (C) 2026 Jack Lloyd +* (C) 2026 Amos Treiber, René Meusel - Rohde & Schwarz Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include "tests.h" + +#if defined(BOTAN_HAS_DTLS_13) + + #include + #include + #include + + #include + #include + #include + #include + +namespace Botan_Tests { + +namespace { + +using namespace Botan; +using namespace Botan::TLS; + +class Journaling_Secret_Logger : public std::enable_shared_from_this { + public: + Botan::TLS::SecretLoggerFn get_secret_logger() { + return [self = weak_from_this()](std::string_view label, std::span secret) { + if(const auto s = self.lock()) { + s->maybe_log_secret(label, secret); + } + }; + } + + void maybe_log_secret(std::string_view label, std::span secret) const { + secrets[std::string(label)] = std::vector(secret.begin(), secret.end()); + } + + public: + mutable std::map> secrets; // NOLINT(*-non-private-member-variable*) +}; + +/// Maximum plaintext size accepted when deprotecting records in these tests +constexpr size_t RECORD_SIZE_LIMIT = 16384; + +constexpr auto epoch_appdata_0 = EpochNumber::create(3); +constexpr auto epoch_appdata_1 = EpochNumber::create(4); +constexpr auto epoch_appdata_4 = EpochNumber::create(7); + +/** + * Creates a client/server pair of DTLS cipher states that share the same + * (artificial) handshake secrets, i.e. records protected by one side can be + * deprotected by the other. + */ +struct DTLS_Peers { + std::unique_ptr client; // NOLINT(*-non-private-member-variables-in-classes) + std::unique_ptr server; // NOLINT(*-non-private-member-variables-in-classes) + + static DTLS_Peers make(const Ciphersuite& cipher) { + const std::vector transcript_hash(HashFunction::create_or_throw(cipher.prf_algo())->output_length(), + 0x00); + auto shared_secret = [] { return secure_vector(32, 0x00); }; + + return DTLS_Peers{ + .client = Cipher_State::init_with_server_hello( + Connection_Side::Client, TLS_Flavor::DTLS, shared_secret(), cipher, transcript_hash, nullptr), + .server = Cipher_State::init_with_server_hello( + Connection_Side::Server, TLS_Flavor::DTLS, shared_secret(), cipher, transcript_hash, nullptr), + }; + } + + /// Advances both peers to the application traffic state (epoch 3) + void advance_to_application_traffic() const { + const std::vector transcript_hash( + HashFunction::create_or_throw(client->hash_algorithm())->output_length(), 0x01); + client->advance_with_server_finished(transcript_hash); + server->advance_with_server_finished(transcript_hash); + client->advance_with_client_finished(transcript_hash); + server->advance_with_client_finished(transcript_hash); + } + + /// Performs a key update in both directions, keeping the peers in sync + void update_keys() const { + client->update_write_keys(); + server->update_read_keys(); + server->update_write_keys(); + client->update_read_keys(); + } +}; + +RecordNumber protect(Cipher_State& cs, + Record_Type type, + std::span payload, + secure_vector& wire, + size_t padding = 0, + std::optional epoch = std::nullopt) { + return as_dtls_cipher_state(&cs)->protect_record(type, payload, padding, wire, epoch); +} + +/// Parses the unified header of a marshalled record as produced by protect() +UnifiedHeader_DTLS parse_header(std::span wire) { + BufferSlicer bs(wire); + return UnifiedHeader_DTLS::parse(bs, std::nullopt /* no CID */); +} + +/// Re-marshall a record with a different header, keeping the payload as-is +secure_vector remarshall_with_header(const UnifiedHeader_DTLS& header, std::span wire) { + BufferSlicer bs(wire); + UnifiedHeader_DTLS::parse(bs, std::nullopt /* no CID */); // skip the original header + const auto payload = bs.take(bs.remaining()); + + auto out = header.serialize>(); + out.insert(out.end(), payload.begin(), payload.end()); + return out; +} + +/// Deprotects a marshalled record as produced by protect() +std::optional deprotect(Cipher_State& cs, std::span wire) { + BufferSlicer bs(wire); + auto header = UnifiedHeader_DTLS::parse(bs, std::nullopt /* no CID */); + const auto payload = bs.take(bs.remaining()); + return as_dtls_cipher_state(&cs)->deprotect_record( + ProtectedRecord_DTLS{.header = header, .payload = secure_vector(payload.begin(), payload.end())}, + RECORD_SIZE_LIMIT); +} + +const Record_Content& record_content(const Record& record) { + return std::visit([](const auto& r) -> const Record_Content& { return r; }, record); +} + +/// The sequence number hint in the unified header (masked, as on the wire) +uint64_t sequence_number_hint(const UnifiedHeader_DTLS& header) { + return std::visit([](const auto seqno) -> uint64_t { return seqno; }, header.sequence_number); +} + +/// Protects a record with @p sender, deprotects it with @p receiver and checks +/// the record number, epoch bits, content type, payload and sequence number. +void check_roundtrip(Test::Result& result, + Cipher_State& sender, + Cipher_State& receiver, + Record_Type type, + std::span payload, + EpochNumber expected_epoch, + uint64_t expected_seqno) { + secure_vector wire; + const auto record_number = protect(sender, type, payload, wire); + + result.test_is_true("epoch of protected record", record_number.epoch == expected_epoch); + result.test_u64_eq("sequence number of protected record", record_number.sequence_number, expected_seqno); + result.test_u8_eq("epoch bits in unified header", + parse_header(wire).epoch_bits, + static_cast(expected_epoch.index() & 0b11)); + + const auto failures_before = receiver.current_read_epoch_deprotection_failures(); + auto record = deprotect(receiver, wire); + result.test_opt_not_null("record was deprotected", record); + if(record.has_value()) { + const auto& content = record_content(*record); + result.test_enum_eq("deprotected record type", content.type, type); + result.test_bin_eq("deprotected payload", content.payload, payload); + result.test_opt_u64_eq("deprotected sequence number", content.sequence_number, expected_seqno); + result.test_is_true("deprotected epoch", content.epoch == expected_epoch); + } + + result.test_u64_eq("successful deprotection does not increment failure counter", + receiver.current_read_epoch_deprotection_failures(), + failures_before); +} + +std::vector update_cipher_state() { + const auto cipher = Ciphersuite::from_name("AES_128_GCM_SHA256").value(); + + auto sl_client = std::make_shared(); + auto sl_server = std::make_shared(); + + const std::vector transcript_hash(32, 0x00); + auto shared_secret = [] { return secure_vector(32, 0x00); }; + + auto cs_server = Cipher_State::init_with_server_hello(Connection_Side::Server, + TLS_Flavor::DTLS, + shared_secret(), + cipher, + transcript_hash, + sl_server->get_secret_logger()); + auto cs_client = Cipher_State::init_with_server_hello(Connection_Side::Client, + TLS_Flavor::DTLS, + shared_secret(), + cipher, + transcript_hash, + sl_client->get_secret_logger()); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + // Unified header: C=0 S=0(8-bit seq) L=0 EE=2 -> 0b00100010 -> 0x22 + // plus 8-bit seq no + const std::vector unified_header = {0x22, 0x00}; + + // reference vectors created via gen_dtls13_cipherstate_vecs.py + const auto c_hs_traffic = + hex_decode("c0 91 0e b2 69 ed 01 50 f6 a8 f3 ea bc 49 0e 58 47 c1 33 9f 43 a1 3f 83 ef b4 ee 71 e4 ef ff ba"); + + const auto s_hs_traffic = + hex_decode("81 9d 08 f9 28 c5 ec 8c ce 7f ed 6f dd b5 d1 ef 48 55 17 50 c1 a3 30 66 c9 fa ea d9 7d 28 c0 99"); + + const auto ciphertext = hex_decode("a6 0c 82 3b bb 98 bf f5 91 9e e8 9b e2 13 8d b8 8d ee 15 df fc 65 b6 07 32 4f"); + + return { + CHECK("key schedule uses 'dtls13' label prefix", + [&](Test::Result& result) { + result.test_bin_eq("client_handshake_traffic_secret", + sl_client->secrets.at("CLIENT_HANDSHAKE_TRAFFIC_SECRET"), + c_hs_traffic); + result.test_bin_eq("server_handshake_traffic_secret", + sl_server->secrets.at("SERVER_HANDSHAKE_TRAFFIC_SECRET"), + s_hs_traffic); + }), + }; +} + +std::vector record_number_handling() { + auto suite_roundtrip = [](const char* suite_name) { + return CHECK(suite_name, [suite_name](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name(suite_name).value()); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + check_roundtrip(result, + *peers.client, + *peers.server, + Record_Type::Handshake, + plaintext, + EpochNumber::handshake_traffic(), + 0); + check_roundtrip(result, + *peers.server, + *peers.client, + Record_Type::Handshake, + plaintext, + EpochNumber::handshake_traffic(), + 0); + }); + }; + + return { + CHECK("records are deprotected out of order within an epoch", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + std::array, 5> wires; + for(auto& wire : wires) { + protect(*peers.client, Record_Type::Handshake, plaintext, wire); + } + + // datagrams may be reordered in transit; the full sequence + // number is reconstructed from the 16-bit hint on the wire + // (RFC 9147 Section 4.2.2) + for(const size_t i : {2, 0, 4, 1, 3}) { + auto record = deprotect(*peers.server, wires[i]); + result.test_opt_not_null("record was deprotected", record); + if(record.has_value()) { + const auto& content = record_content(*record); + result.test_opt_u64_eq("reconstructed sequence number", content.sequence_number, i); + result.test_bin_eq("deprotected payload", content.payload, plaintext); + } + } + }), + + CHECK("sequence numbers are masked on the wire", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + std::array, 3> wires; + for(size_t i = 0; i < wires.size(); ++i) { + const auto record_number = protect(*peers.client, Record_Type::Handshake, plaintext, wires[i]); + result.test_u64_eq("sequence number of protected record", record_number.sequence_number, i); + + // RFC 9147 Section 4.2.3 + // The encrypted sequence number is computed by XORing the + // leading bytes of the mask with the on-the-wire + // representation of the sequence number. + result.test_is_true("sequence number is masked on the wire", + sequence_number_hint(parse_header(wires[i])) != i); + } + + for(size_t i = 0; i < wires.size(); ++i) { + auto record = deprotect(*peers.server, wires[i]); + result.test_opt_not_null("record was deprotected", record); + if(record.has_value()) { + result.test_opt_u64_eq("recovered sequence number", record_content(*record).sequence_number, i); + } + } + }), + + // round trips covering the AES-256 and ChaCha20 record number mask + // constructions (AES-128 is covered by the test above) + suite_roundtrip("AES_256_GCM_SHA384"), + suite_roundtrip("AES_128_CCM_SHA256"), + suite_roundtrip("CHACHA20_POLY1305_SHA256"), + }; +} + +std::vector epoch_transitions() { + return { + CHECK("records round trip across epochs", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + result.test_is_true("client write epoch", + peers.client->current_write_epoch_number().is_handshake_traffic()); + result.test_is_true("server read epoch", + peers.server->current_read_epoch_number().is_handshake_traffic()); + + check_roundtrip(result, + *peers.client, + *peers.server, + Record_Type::Handshake, + plaintext, + EpochNumber::handshake_traffic(), + 0); + check_roundtrip(result, + *peers.client, + *peers.server, + Record_Type::Handshake, + plaintext, + EpochNumber::handshake_traffic(), + 1); + + secure_vector tampered_wire; + protect(*peers.client, Record_Type::Handshake, plaintext, tampered_wire); + tampered_wire.back() ^= 0x01; + result.test_opt_is_null("tampered handshake record discarded", deprotect(*peers.server, tampered_wire)); + result.test_u64_eq("failed deprotections counted in handshake read epoch", + peers.server->current_read_epoch_deprotection_failures(), + 1); + + peers.advance_to_application_traffic(); + + result.test_is_true("client write epoch", + peers.client->current_write_epoch_number().application_traffic_index() == 0); + result.test_is_true("server read epoch", + peers.server->current_read_epoch_number().application_traffic_index() == 0); + result.test_u64_eq("deprotection failure counter reset after read epoch advance", + peers.server->current_read_epoch_deprotection_failures(), + 0); + + // sequence numbers restart at 0 in the new epoch + constexpr auto epocho_appdata_0 = EpochNumber::create(3); + check_roundtrip( + result, *peers.client, *peers.server, Record_Type::ApplicationData, plaintext, epocho_appdata_0, 0); + check_roundtrip( + result, *peers.server, *peers.client, Record_Type::ApplicationData, plaintext, epocho_appdata_0, 0); + check_roundtrip( + result, *peers.server, *peers.client, Record_Type::ApplicationData, plaintext, epocho_appdata_0, 1); + }), + + CHECK("records can be protected under the previous epoch", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + peers.advance_to_application_traffic(); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + // e.g. a handshake flight retransmission after application + // traffic keys are already available + secure_vector wire; + const auto record_number = + protect(*peers.client, Record_Type::Handshake, plaintext, wire, 0, EpochNumber::handshake_traffic()); + result.test_is_true("protected under handshake epoch", record_number.epoch.is_handshake_traffic()); + result.test_u64_eq("sequence number of protected record", record_number.sequence_number, 0); + result.test_u8_eq("epoch bits in unified header", parse_header(wire).epoch_bits, 0b10); + + auto record = deprotect(*peers.server, wire); + result.test_opt_not_null("record was deprotected", record); + if(record.has_value()) { + const auto& content = record_content(*record); + result.test_enum_eq("deprotected record type", content.type, Record_Type::Handshake); + result.test_bin_eq("deprotected payload", content.payload, plaintext); + result.test_is_true("deprotected epoch", content.epoch->is_handshake_traffic()); + } + }), + + CHECK("records round trip after key update with previous epoch retained", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + peers.advance_to_application_traffic(); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + // protect a record under the initial application traffic epoch + secure_vector old_wire; + protect(*peers.client, Record_Type::ApplicationData, plaintext, old_wire); + + peers.update_keys(); + + result.test_is_true("client write epoch after key update", + peers.client->current_write_epoch_number().application_traffic_index() == 1); + + // sequence numbers restart at 0 in the new epoch + check_roundtrip( + result, *peers.client, *peers.server, Record_Type::ApplicationData, plaintext, epoch_appdata_1, 0); + check_roundtrip( + result, *peers.server, *peers.client, Record_Type::ApplicationData, plaintext, epoch_appdata_1, 0); + + // records from the retained previous epoch can still be deprotected + auto old_record = deprotect(*peers.server, old_wire); + result.test_opt_not_null("record from previous epoch was deprotected", old_record); + if(old_record.has_value()) { + const auto& content = record_content(*old_record); + result.test_bin_eq("deprotected payload", content.payload, plaintext); + result.test_is_true("deprotected epoch", content.epoch->application_traffic_index() == 0); + } + }), + + CHECK("deprotection uses the newest epoch matching the epoch bits", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + peers.advance_to_application_traffic(); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + // retain a record protected under the initial application + // traffic epoch 3 (epoch bits 0b11) + secure_vector epoch3_wire; + protect(*peers.client, Record_Type::ApplicationData, plaintext, epoch3_wire); + + // perform several key updates without pruning, so that multiple + // read epochs share the same epoch bits (epochs 3 and 7 -> 0b11) + for(size_t i = 0; i < 4; ++i) { + peers.update_keys(); + } + + result.test_is_true("client write epoch", + peers.client->current_write_epoch_number().application_traffic_index() == 4); + + // the record's epoch bits (0b11) match both the current epoch 7 + // and the retained epoch 3; deprotection only succeeds if the + // newest matching epoch is used (RFC 9147 Section 4.2.2) + check_roundtrip( + result, *peers.client, *peers.server, Record_Type::ApplicationData, plaintext, epoch_appdata_4, 0); + check_roundtrip( + result, *peers.server, *peers.client, Record_Type::ApplicationData, plaintext, epoch_appdata_4, 0); + + // the epoch-3 record is now ambiguous with epoch 7; it is + // (unsuccessfully) attempted under the newest matching epoch + // and thus silently discarded (RFC 9147 Sections 4.2.2, 4.5.2) + result.test_opt_is_null("record from ambiguous previous epoch was discarded", + deprotect(*peers.server, epoch3_wire)); + + // deprotecting under the newest matching epoch did not poison + // the cipher state for the current epoch + check_roundtrip( + result, *peers.client, *peers.server, Record_Type::ApplicationData, plaintext, epoch_appdata_4, 1); + }), + }; +} + +std::vector epoch_pruning() { + return { + CHECK("records of pruned read epochs are silently discarded", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + peers.advance_to_application_traffic(); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + secure_vector old_wire; + protect(*peers.client, Record_Type::ApplicationData, plaintext, old_wire); + + peers.update_keys(); + + as_dtls_cipher_state(peers.server.get())->prune_read_epochs_older_than(epoch_appdata_1); + + result.test_opt_is_null("record from pruned epoch was discarded", deprotect(*peers.server, old_wire)); + + // the current epoch is not affected by the pruning + check_roundtrip( + result, *peers.client, *peers.server, Record_Type::ApplicationData, plaintext, epoch_appdata_1, 0); + }), + + CHECK("protecting under a pruned write epoch fails", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + peers.advance_to_application_traffic(); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + peers.update_keys(); + + as_dtls_cipher_state(peers.client.get())->prune_write_epochs_older_than(epoch_appdata_1); + + result.test_throws( + "no write epoch for pruned epoch number", "No write epoch found for requested epoch number", [&] { + secure_vector wire; + protect(*peers.client, Record_Type::ApplicationData, plaintext, wire, 0, epoch_appdata_0); + }); + + // the current epoch is not affected by the pruning + check_roundtrip( + result, *peers.client, *peers.server, Record_Type::ApplicationData, plaintext, epoch_appdata_1, 0); + }), + }; +} + +std::vector invalid_records() { + return { + CHECK("tampered records are silently discarded", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + peers.advance_to_application_traffic(); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + secure_vector wire; + protect(*peers.client, Record_Type::ApplicationData, plaintext, wire); + + // RFC 9147 Section 4.5.2 + // Unlike TLS, DTLS is resilient in the face of invalid + // records [...]. In general, invalid records SHOULD be + // silently discarded [...]. + auto tampered_ciphertext = wire; + tampered_ciphertext.back() ^= 0x01; + result.test_opt_is_null("tampered ciphertext was discarded", + deprotect(*peers.server, tampered_ciphertext)); + result.test_u64_eq("tampered ciphertext increments failure counter", + peers.server->current_read_epoch_deprotection_failures(), + 1); + + // the masked sequence number hint is part of the associated data + auto tampered_hint = parse_header(wire); + tampered_hint.sequence_number = std::visit( + [](const auto seqno) -> SequenceNumberHint { return static_cast(seqno ^ 0x01); }, + tampered_hint.sequence_number); + result.test_opt_is_null("tampered header was discarded", + deprotect(*peers.server, remarshall_with_header(tampered_hint, wire))); + result.test_u64_eq("tampered header increments failure counter", + peers.server->current_read_epoch_deprotection_failures(), + 2); + + // epoch bits that match no known epoch (e.g. early traffic) + auto unknown_epoch = parse_header(wire); + unknown_epoch.epoch_bits = 0b01; + result.test_opt_is_null("record with unknown epoch was discarded", + deprotect(*peers.server, remarshall_with_header(unknown_epoch, wire))); + result.test_u64_eq("unknown epoch does not increment failure counter", + peers.server->current_read_epoch_deprotection_failures(), + 2); + + // the failed attempts must not poison the cipher state + result.test_opt_not_null("untampered record was deprotected", deprotect(*peers.server, wire)); + result.test_u64_eq("successful deprotection leaves failure counter unchanged", + peers.server->current_read_epoch_deprotection_failures(), + 2); + + check_roundtrip( + result, *peers.client, *peers.server, Record_Type::ApplicationData, plaintext, epoch_appdata_0, 1); + }), + + CHECK("authenticated records with disallowed content types are rejected", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + peers.advance_to_application_traffic(); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + // RFC 9147 Section 4.1 Figure 5: ChangeCipherSpec (20) is not a + // valid content type for protected DTLS 1.3 records + secure_vector ccs_wire; + protect(*peers.client, Record_Type::ChangeCipherSpec, plaintext, ccs_wire); + result.test_throws("unexpected content type", + "Deprotected DTLS record had unexpected content type: 20", + [&] { deprotect(*peers.server, ccs_wire); }); + + // RFC 9147 Section 6.1: application data must not appear in the + // handshake epoch + secure_vector interleaved_wire; + protect(*peers.client, + Record_Type::ApplicationData, + plaintext, + interleaved_wire, + 0, + EpochNumber::handshake_traffic()); + result.test_throws("application data in handshake epoch", + "Can't interleave application and handshake data", + [&] { deprotect(*peers.server, interleaved_wire); }); + }), + }; +} + +std::vector record_padding() { + return { + CHECK("short records are padded to the minimum ciphertext size", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_CCM_8_SHA256").value()); + peers.advance_to_application_traffic(); + + const std::span empty_payload; + + secure_vector wire; + protect(*peers.client, Record_Type::ApplicationData, empty_payload, wire); + result.test_sz_eq( + "ciphertext was padded to 16 bytes", wire.size() - parse_header(wire).serialized_byte_length(), 16); + + auto record = deprotect(*peers.server, wire); + result.test_opt_not_null("record was deprotected", record); + if(record.has_value()) { + const auto& content = record_content(*record); + result.test_enum_eq("deprotected record type", content.type, Record_Type::ApplicationData); + result.test_is_true("deprotected payload is empty", content.payload.empty()); + } + }), + + CHECK("explicitly padded records round trip", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + peers.advance_to_application_traffic(); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" (10 bytes) + + secure_vector wire; + protect(*peers.client, Record_Type::ApplicationData, plaintext, wire, 64 /* padding bytes */); + + // 10 content bytes + 1 type byte + 64 padding bytes + 16 tag bytes + result.test_sz_eq( + "ciphertext size", wire.size() - parse_header(wire).serialized_byte_length(), 10 + 1 + 64 + 16); + + auto record = deprotect(*peers.server, wire); + result.test_opt_not_null("record was deprotected", record); + if(record.has_value()) { + result.test_bin_eq("deprotected payload without padding", record_content(*record).payload, plaintext); + } + }), + }; +} + +std::vector clearing_keys() { + return { + CHECK( + "protect and deprotect fail after clearing the respective keys", + [&](Test::Result& result) { + auto peers = DTLS_Peers::make(Ciphersuite::from_name("AES_128_GCM_SHA256").value()); + + const auto plaintext = hex_decode_locked("68656c6c6f2064746c73"); // "hello dtls" + + result.test_is_true("cryptographic association established", peers.client->has_cryptographic_association()); + result.test_is_true("cryptographic association established", peers.server->has_cryptographic_association()); + + secure_vector wire; + protect(*peers.client, Record_Type::Handshake, plaintext, wire); + + peers.server->clear_read_keys(); + result.test_is_false("no cryptographic association", peers.server->has_cryptographic_association()); + result.test_throws("deprotect without read keys", + [&] { deprotect(*peers.server, wire); }); + + peers.client->clear_write_keys(); + result.test_is_false("no cryptographic association", peers.client->has_cryptographic_association()); + result.test_throws("protect without write keys", [&] { + secure_vector w; + protect(*peers.client, Record_Type::Handshake, plaintext, w); + }); + }), + }; +} + +} // namespace + +BOTAN_REGISTER_TEST_FN("tls", + "dtls_cipher_state", + update_cipher_state, + record_number_handling, + epoch_transitions, + epoch_pruning, + invalid_records, + record_padding, + clearing_keys); + +} // namespace Botan_Tests + +#endif diff --git a/src/tests/test_tls_dtls13_handshake_layer.cpp b/src/tests/test_tls_dtls13_handshake_layer.cpp new file mode 100644 index 00000000000..8aeef2fad60 --- /dev/null +++ b/src/tests/test_tls_dtls13_handshake_layer.cpp @@ -0,0 +1,941 @@ +/* +* (C) 2026 Jack Lloyd +* (C) 2026 Amos Treiber, René Meusel - Rohde & Schwarz Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include "tests.h" + +#if defined(BOTAN_HAS_DTLS_13) + #include + + #include + #include + + #include + #include + #include + #include + #include + #include + +namespace TLS = Botan::TLS; + +namespace Botan_Tests { + +namespace { + +constexpr auto epoch_appdata_0 = TLS::EpochNumber::create(3); +constexpr auto epoch_appdata_1 = TLS::EpochNumber::create(4); + +using CopyDataResult = TLS::Handshake_Layer::CopyDataResult; + +std::unique_ptr make_handshake_layer(TLS::Connection_Side side) { + return std::make_unique(side); +} + +TLS::Handshake_Record handshake_record(std::span bytes, + TLS::EpochNumber epoch = TLS::EpochNumber::handshake_traffic()) { + return TLS::Handshake_Record{{ + .type = TLS::Record_Type::Handshake, + .sequence_number = std::nullopt, + .payload = Botan::secure_vector(bytes.begin(), bytes.end()), + .epoch = epoch, + }}; +} + +std::vector concat_fragments(Test::Result& result, + std::span fragments) { + std::vector msg; + for(const auto& fragment : fragments) { + result.require("fragment has a header", fragment.size() > 12); + msg.insert(msg.end(), fragment.begin() + 12 /* skip header */, fragment.end()); + } + return msg; +} + +/** + * @returns bytes of a full DTLS client hello record without fragmentation + */ +std::vector client_hello_record_bytes() { + return Botan::hex_decode( // from wolfssl + "16 fe fd 00 00 00 00 00 00 00 00 01 fa 01 00 01 ee 00 00 00 00" + "00 00 01 ee fe fd 9a 71 88 3e 33 0e f5 ac f3 1a 3e 34 b6 28 59" + "cf b5 4b 25 14 e9 fd 7a 88 56 7b 3c 91 56 76 3a 4e 00 00 00 36" + "13 02 13 01 13 03 c0 2c c0 2b c0 30 c0 2f 00 9f 00 9e cc a9 cc" + "a8 cc aa c0 27 c0 23 c0 28 c0 24 c0 0a c0 09 c0 14 c0 13 00 6b" + "00 67 00 39 00 33 cc 14 cc 13 cc 15 01 00 01 8e 00 2b 00 03 02" + "fe fc 00 0d 00 1c 00 1a 06 03 05 03 04 03 08 06 08 0b 08 05 08" + "0a 08 04 08 09 06 01 05 01 04 01 03 01 00 0a 00 10 00 0e 11 ed" + "11 eb 00 19 00 18 00 17 00 15 01 00 00 16 00 00 00 33 01 4b 01" + "49 00 17 00 41 04 9d 51 3d c7 9b ad 20 a2 4d 54 f7 24 72 ea 25" + "df 33 0f 51 7e c6 69 34 db 6b 20 52 94 74 ee 2b 4e 3d ad 4b 5d" + "d6 83 df 82 13 90 be f2 b6 55 67 87 cd a4 30 37 62 e0 6e 45 31" + "04 1a 5e d0 56 17 97 01 00 01 00 13 9d f5 5b 77 eb 78 86 b2 87" + "e4 f7 28 7b 09 62 99 ca 70 30 0a 7a 5d 1f 1a fd 78 fd 6a 7b 49" + "49 ac 66 49 62 48 a7 bc 05 37 cd f0 c3 95 f4 f1 e5 d1 07 dc 8a" + "48 4a 2a 73 c2 0f 2d 29 66 8f e2 33 69 79 f9 df c8 91 99 20 e4" + "dc 6d 56 e4 a9 34 bd f5 bc d8 05 b6 f7 de 6c 0b 29 81 7b 60 c5" + "58 2d 76 7c 4b d9 59 84 65 bb 19 90 a4 13 e4 69 db 5d 2b 7d 03" + "c3 ef f1 fe 1d f6 3e 9b af fd 69 48 31 74 1a 54 6b 43 05 1c ae" + "08 90 6d 4e 8b b4 86 e9 90 58 1e bb 34 06 9b 31 eb 11 18 4c aa" + "84 14 a0 04 0f 71 1b 09 93 c2 b2 ca 0e c1 53 2b 9e 2c 5e 24 92" + "73 09 72 54 82 40 14 a8 48 9c 9e ab 80 31 36 2c b1 5d fd b7 c1" + "65 bb b6 c4 e1 9f 0c 53 5c 8d 08 95 28 9c 7a 69 b4 2c 4e 5a b0" + "b4 9f a1 b3 cd d9 ff 37 78 2d 1f cf ff 4d 76 32 6c d5 fc eb 1a" + "2c e2 9e 04 85 d3 af 10 3c 4c fa b6 6e 47 66"); +} + +/** + * @returns bytes of a full DTLS encrypted extensions message (without headers) + */ +std::vector client_finished_bare_bytes() { + return Botan::hex_decode( + "a8 ec 43 6d 67 76 34 ae 52 5a c1 fc eb e1 1a 03 9e c1 76 94 fa" + "c6 e9 85 27 b6 42 f2 ed d5 ce 61"); +} + +/** + * @returns bytes of a client Certificate message with an empty certificate + * list (i.e. a client without credentials, RFC 8446 4.4.2) + */ +std::vector client_certificate_bare_bytes() { + return {0x00 /* empty request context */, 0x00, 0x00, 0x00 /* empty certificate list */}; +} + +/** + * @returns bytes of a CertificateVerify message (ecdsa_secp256r1_sha256 with an + * empty -- hence invalid -- signature; parsing does not verify it) + */ +std::vector certificate_verify_bare_bytes() { + return {0x04, 0x03 /* ecdsa_secp256r1_sha256 */, 0x00, 0x00 /* empty signature */}; +} + +/** + * @returns bytes of a minimal NewSessionTicket message (RFC 8446 4.6.1) + */ +std::vector new_session_ticket_bare_bytes() { + return Botan::hex_decode( + "00 00 0e 10" // ticket_lifetime: 3600 seconds + "00 00 00 00" // ticket_age_add + "00" // empty ticket_nonce + "00 01 aa" // ticket: 1 byte + "00 00"); // no extensions +} + +/** + * @returns bytes of a full DTLS client hello message with handshake protocol + * header without fragmentation + */ +std::vector client_hello_marshalled_bytes() { + const auto client_hello_record = client_hello_record_bytes(); + const auto client_hello_bytes = std::span{client_hello_record}.subspan(13 /* record header */); + return {client_hello_bytes.begin(), client_hello_bytes.end()}; +} + +/** + * @returns bytes of a full DTLS client hello message + */ +std::vector client_hello_bare_bytes() { + const auto client_hello_record = client_hello_record_bytes(); + const auto bare_client_hello_bytes = + std::span{client_hello_record}.subspan(13 /* record header */ + 12 /* HS msg header */); + return {bare_client_hello_bytes.begin(), bare_client_hello_bytes.end()}; +} + +/** + * @returns a DTLS ClientHello object + */ +TLS::Client_Hello_13 client_hello() { + return std::get( + TLS::Client_Hello_13::parse(client_hello_bare_bytes(), Botan::TLS::TLS_Flavor::DTLS)); +} + +/** + * @returns the bytes of a SHA-256 transcript hash of client_hello() +*/ +std::vector client_hello_transcript_hash() { + return Botan::hex_decode("2AABAE13B1D3CC208A6E37F3B91B46C101DD1B96E0731A04DC379A79186C86CF"); +} + +/** + * Frames a single DTLS handshake message fragment (RFC 9147 5.2) by prepending + * the msg_type/length/message_seq/fragment_offset/fragment_length header. + */ +std::vector dtls_marshall_fragment(TLS::Handshake_Type type, + size_t total_len, + uint16_t msg_seq, + size_t frag_offset, + std::span fragment) { + auto store_be24 = [](uint32_t value) { + BOTAN_ASSERT_NOMSG(value <= 0xFFFFFF); + const auto be = Botan::store_be(value); + std::array result{}; + Botan::copy_mem(result, std::span{be}.last<3>()); + return result; + }; + + return Botan::concat>( // + Botan::store_be(type), + store_be24(static_cast(total_len)), + Botan::store_be(msg_seq), + store_be24(static_cast(frag_offset)), + store_be24(static_cast(fragment.size())), + fragment); +} + +/** + * One slice of a handshake message, to be wrapped into an individual DTLS + * handshake fragment (see dtls_marshall_fragment()). + */ +struct Fragment_Piece { + size_t offset; + std::span bytes; +}; + +/** + * Splits @p message into consecutive, non-overlapping pieces of the given + * @p sizes (which must sum up to message.size()). The resulting pieces span into the original message, + * so the caller must ensure that the original message remains valid for the lifetime of the pieces. + */ +std::vector split_into_pieces(std::span message, std::span sizes) { + BOTAN_ASSERT_NOMSG(std::accumulate(sizes.begin(), sizes.end(), size_t{0}) == message.size()); + std::vector pieces; + pieces.reserve(sizes.size()); + + Botan::BufferSlicer bs(message); + while(!bs.empty() && pieces.size() < sizes.size()) { + const auto offset = message.size() - bs.remaining(); + const auto bytes_in_this_piece = std::min(bs.remaining(), sizes[pieces.size()]); + pieces.emplace_back(Fragment_Piece{offset, bs.take(bytes_in_this_piece)}); + } + + BOTAN_ASSERT_NOMSG(pieces.size() == sizes.size()); + return pieces; +} + +/** + * @returns @p count roughly equally sized pieces covering @p total bytes + * (the remainder is added to the last piece) + */ +std::vector equal_sizes(size_t total, size_t count) { + std::vector sizes(count, total / count); + sizes.back() += total - (total / count) * count; + return sizes; +} + +std::vector basic() { + const auto default_policy = TLS::Policy(); + + return { + CHECK("read ClientHello", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto transcript_hash = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + result.require("successful ingestion", + hl->copy_data(default_policy, handshake_record(client_hello_marshalled_bytes())) == + CopyDataResult::Consumed); + auto msg = hl->next_message(default_policy, transcript_hash); + result.require("received something", msg.has_value()); + result.test_u64_eq("message index is 0", msg->index(), 0); + result.require("message is ClientHello", std::holds_alternative(msg.value())); + + result.test_bin_eq("received handshake message", + std::get(msg.value()).serialize(), + client_hello_bare_bytes()); + + transcript_hash.set_algorithm("SHA-256"); + result.test_bin_eq("transcript hash", transcript_hash.current(), client_hello_transcript_hash()); + + result.test_opt_is_null("no more records", hl->next_message(default_policy, transcript_hash)); + }), + + CHECK("prepare ClientHello", + [&](Test::Result& result) { + auto hello = client_hello(); + auto hl = make_handshake_layer(TLS::Connection_Side::Client); + + // Creating a fresh handshake layer message for the TLS ClientHello should result in the + // same bytes as the handshake msg header in client_hello_record + result.test_bin_eq( + "reproduces wire message", + hl->fragment_message( + hello.wire_type(), TLS::Handshake_Layer::serialize(hello), TLS::MAX_PLAINTEXT_SIZE)[0], + client_hello_marshalled_bytes()); + }), + + CHECK("prepare ClientHello with fragmentation", + [&](Test::Result& result) { + auto hello = client_hello(); + auto hl = make_handshake_layer(TLS::Connection_Side::Client); + + // Force fragmentation into two or more fragments + const size_t fragment_size = client_hello_bare_bytes().size() / 2; + + // Creating a fresh handshake layer message for the TLS ClientHello should result in the + // same bytes as the handshake msg header in client_hello_record + const auto fragments = hl->fragment_message( + hello.wire_type(), TLS::Handshake_Layer::serialize(hello), static_cast(fragment_size)); + result.test_is_true("fragmented", fragments.size() > 1); + + result.test_bin_eq( + "reproduces full message", concat_fragments(result, fragments), client_hello_bare_bytes()); + + // The first fragment can be capped individually, e.g. to fill up a + // record that already holds fragments of previous messages. + constexpr uint16_t first_fragment_size = 64; + const auto capped_fragments = hl->fragment_message(hello.wire_type(), + TLS::Handshake_Layer::serialize(hello), + static_cast(fragment_size), + first_fragment_size); + result.test_is_true("fragmented", capped_fragments.size() > 1); + result.test_sz_eq( + "first fragment respects its individual cap", capped_fragments.front().size(), first_fragment_size); + result.test_sz_eq("second fragment uses the full budget", capped_fragments[1].size(), fragment_size); + result.test_bin_eq( + "reproduces full message", concat_fragments(result, capped_fragments), client_hello_bare_bytes()); + + result.test_throws("first fragment cap must not exceed the general cap", [&] { + static_cast(hl->fragment_message(hello.wire_type(), + TLS::Handshake_Layer::serialize(hello), + first_fragment_size, + static_cast(fragment_size))); + }); + + result.test_throws("fragment size must exceed the fragment header length", [&] { + static_cast(hl->fragment_message(hello.wire_type(), + TLS::Handshake_Layer::serialize(hello), + TLS::DTLS_Handshake_Layer::FRAGMENT_HEADER_LENGTH)); + }); + }), + + CHECK("parse ClientHello with fragmentation", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + // Split the ClientHello into two fragments + const auto client_hello_bytes = client_hello_bare_bytes(); + const size_t fragment_size = client_hello_bytes.size() / 2; + + // Prepend HS headers + const auto first_fragment_framed = + dtls_marshall_fragment(TLS::Handshake_Type::ClientHello, + client_hello_bytes.size(), + 0 /* msg_seq */, + 0 /*frag_offset */, + std::span{client_hello_bytes}.subspan(0, fragment_size)); + const auto second_fragment_framed = + dtls_marshall_fragment(TLS::Handshake_Type::ClientHello, + client_hello_bytes.size(), + 0 /* msg_seq */, + fragment_size /*frag_offset */, + std::span{client_hello_bytes}.subspan(fragment_size)); + + result.require( + "successful ingestion", + hl->copy_data(default_policy, handshake_record(first_fragment_framed)) == CopyDataResult::Consumed); + result.test_opt_is_null("needs more bytes", hl->next_message(default_policy, th)); + result.test_is_true("holds pending message data", hl->has_pending_data()); + + result.require( + "successful ingestion", + hl->copy_data(default_policy, handshake_record(second_fragment_framed)) == CopyDataResult::Consumed); + auto msg = hl->next_message(default_policy, th); + result.require("received something", msg.has_value()); + result.require("message is ClientHello", std::holds_alternative(msg.value())); + + result.test_bin_eq("received handshake message", + std::get(msg.value()).serialize(), + client_hello_bare_bytes()); + + th.set_algorithm("SHA-256"); + result.test_bin_eq("transcript hash", th.current(), client_hello_transcript_hash()); + + result.test_opt_is_null("no more records", hl->next_message(default_policy, th)); + }), + + CHECK("Messages are emitted in order of their sequence number", + [&](Test::Result& result) { + const auto ch = client_hello_bare_bytes(); + const auto cc = client_certificate_bare_bytes(); + const auto cv = certificate_verify_bare_bytes(); + const auto cf = client_finished_bare_bytes(); + + constexpr uint16_t window = TLS::DTLS_Handshake_Layer::MAX_BUFFERED_FUTURE_MESSAGES; + auto marshalled_finished = [&](uint16_t seqno) { + return dtls_marshall_fragment(TLS::Handshake_Type::Finished, cf.size(), seqno, 0, cf); + }; + auto marshalled_client_hello = [&](uint16_t seqno) { + return dtls_marshall_fragment(TLS::Handshake_Type::ClientHello, ch.size(), seqno, 0, ch); + }; + + // Buffering window semantics for out-of-order messages. Messages + // too far in the future are discarded right away, messages within + // the window are buffered for reassembly (RFC 9147 5.2). + // + // The messages buffered here are deliberately never pulled: they + // could only be emitted after a ClientHello or Finished, both of + // which must be the final pending message when pulled because they + // may immediately precede a key change (RFC 9846 5.1). + { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto transcript_hash = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + result.test_enum_eq("message beyond the buffering window is discarded", + hl->copy_data(default_policy, handshake_record(marshalled_finished(window + 1))), + CopyDataResult::Discarded); + result.test_enum_eq("message at the edge of the buffering window is buffered", + hl->copy_data(default_policy, handshake_record(marshalled_finished(window))), + CopyDataResult::Consumed); + + // A record that mixes a bufferable fragment with one beyond the + // window is consumed partially. + const auto mixed_record = + Botan::concat>(marshalled_client_hello(1), marshalled_finished(window + 1)); + result.test_enum_eq("record with discarded and buffered fragments is consumed partially", + hl->copy_data(default_policy, handshake_record(mixed_record)), + CopyDataResult::ConsumedPartially); + + // Nothing is emitted as long as the start of the sequence space + // is missing. + result.test_opt_is_null("no message to read yet", hl->next_message(default_policy, transcript_hash)); + } + + // Messages are emitted in order of their sequence number. Each + // ClientHello and the final Finished are pulled without further + // pending data, as they must align with a record boundary + // (RFC 9846 5.1). + { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto transcript_hash = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + result.require("successful ingestion of seqno 0", + hl->copy_data(default_policy, handshake_record(marshalled_client_hello(0))) == + CopyDataResult::Consumed); + result.test_is_true("received message 0", + std::holds_alternative( + hl->next_message(default_policy, transcript_hash).value())); + + // The second ClientHello (seqno 1) reflects the HelloRetryRequest + // case (RFC 8446 4.1.4). + result.require("successful ingestion of seqno 1", + hl->copy_data(default_policy, handshake_record(marshalled_client_hello(1))) == + CopyDataResult::Consumed); + result.test_is_true("received message 1", + std::holds_alternative( + hl->next_message(default_policy, transcript_hash).value())); + + // Buffer the Finished message that will complete the client + // authentication flight Certificate(2), CertificateVerify(3), + // Finished(4) further down (RFC 8446 4.4). + result.test_enum_eq("Finished of the client authentication flight is buffered", + hl->copy_data(default_policy, handshake_record(marshalled_finished(4))), + CopyDataResult::Consumed); + + // The buffered Finished cannot be emitted before the gap in the + // sequence space is filled. + result.test_opt_is_null("buffered future message is not emitted out of order", + hl->next_message(default_policy, transcript_hash)); + + result.test_enum_eq( + "successful ingestion of Certificate", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + TLS::Handshake_Type::Certificate, cc.size(), 2 /* seqno */, 0, cc))), + CopyDataResult::Consumed); + result.test_enum_eq( + "successful ingestion of CertificateVerify", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + TLS::Handshake_Type::CertificateVerify, cv.size(), 3 /* seqno */, 0, cv))), + CopyDataResult::Consumed); + + // The buffered messages are emitted in order of their sequence + // numbers, ending with the Finished buffered further up. Because + // the gap fillers use different message types, the final message + // is provably the originally buffered one. + result.test_is_true("received message 2", + std::holds_alternative( + hl->next_message(default_policy, transcript_hash).value())); + result.test_is_true("received message 3", + std::holds_alternative( + hl->next_message(default_policy, transcript_hash).value())); + result.test_is_true("originally buffered Finished is emitted last", + std::holds_alternative( + hl->next_message(default_policy, transcript_hash).value())); + + result.test_opt_is_null("no more messages", hl->next_message(default_policy, transcript_hash)); + } + }), + }; +} + +std::vector fragmentation() { + const auto default_policy = TLS::Policy(); + const auto type = TLS::Handshake_Type::ClientHello; + constexpr uint16_t msg_seq = 0; + + auto verify_client_hello = + [](Test::Result& result, const std::optional& msg, TLS::Transcript_Hash_State& th) { + result.require("received something", msg.has_value()); + th.set_algorithm("SHA-256"); + result.test_bin_eq("transcript hash", th.current(), client_hello_transcript_hash()); + result.require("message is ClientHello", std::holds_alternative(msg.value())); + result.test_bin_eq("received handshake message", + std::get(msg.value()).serialize(), + client_hello_bare_bytes()); + }; + + return { + CHECK("parse ClientHello reassembled from many small fragments", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto message = client_hello_bare_bytes(); + const auto pieces = split_into_pieces(message, equal_sizes(message.size(), 31)); + + std::optional msg; + for(size_t i = 0; i < pieces.size(); ++i) { + result.require("successful ingestion", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, pieces[i].offset, pieces[i].bytes))) == + CopyDataResult::Consumed); + msg = hl->next_message(default_policy, th); + const bool is_last = (i + 1 == pieces.size()); + result.test_is_true(is_last ? "complete after last fragment" : "still incomplete", + msg.has_value() == is_last); + } + + verify_client_hello(result, msg, th); + }), + + CHECK("parse ClientHello with multiple fragments in a single record", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto message = client_hello_bare_bytes(); + const auto pieces = split_into_pieces(message, equal_sizes(message.size(), 31)); + + const auto record_with_multiple_fragments = [&]() { + std::vector record; + for(const auto& piece : pieces) { + const auto fragment = + dtls_marshall_fragment(type, message.size(), msg_seq, piece.offset, piece.bytes); + record.insert(record.end(), fragment.begin(), fragment.end()); + } + return record; + }(); + + result.require("successful ingestion", + hl->copy_data(default_policy, handshake_record(record_with_multiple_fragments)) == + CopyDataResult::Consumed); + + verify_client_hello(result, hl->next_message(default_policy, th), th); + }), + + CHECK("parse ClientHello reassembled from unevenly sized fragments", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto message = client_hello_bare_bytes(); + const size_t a = message.size() / 10; + const size_t b = message.size() / 3; + const size_t c = message.size() / 20 + 1; + const size_t d = message.size() - a - b - c; + const auto pieces = split_into_pieces(message, std::array{a, b, c, d}); + + for(const auto& piece : pieces) { + result.require("successful ingestion", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, piece.offset, piece.bytes))) == + CopyDataResult::Consumed); + } + + auto msg = hl->next_message(default_policy, th); + + verify_client_hello(result, msg, th); + }), + + CHECK("parse ClientHello reassembled from fragments delivered out of order", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto message = client_hello_bare_bytes(); + const auto pieces = split_into_pieces(message, equal_sizes(message.size(), 4)); + + // deliberately not in ascending offset order + const auto delivery_order = std::array{2, 0, 3, 1}; + result.require("delivery order matches pieces", delivery_order.size() == pieces.size()); + + std::optional msg; + for(size_t i = 0; i < delivery_order.size(); ++i) { + const auto& piece = pieces[delivery_order[i]]; + result.require("successful ingestion", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, piece.offset, piece.bytes))) == + CopyDataResult::Consumed); + msg = hl->next_message(default_policy, th); + const bool is_last = (i + 1 == delivery_order.size()); + result.test_is_true(is_last ? "complete after last fragment" : "still incomplete", + msg.has_value() == is_last); + } + + verify_client_hello(result, msg, th); + }), + + CHECK("parse ClientHello reassembled from overlapping fragments", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto message = client_hello_bare_bytes(); + const size_t mid = message.size() / 2; + const size_t overlap = 20; + result.require("overlap smaller than half the message", overlap + mid < message.size()); + + // first fragment: [0, mid + overlap) + // second fragment: [mid, message.size()) + // -> bytes [mid, mid + overlap) are covered by both fragments with identical content + const auto first_span = std::span{message}.first(mid + overlap); + const auto second_span = std::span{message}.subspan(mid); + + result.require( + "successful ingestion", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, 0, first_span))) == CopyDataResult::Consumed); + result.test_opt_is_null("still incomplete", hl->next_message(default_policy, th)); + + result.require( + "successful ingestion", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, mid, second_span))) == CopyDataResult::Consumed); + + auto msg = hl->next_message(default_policy, th); + + verify_client_hello(result, msg, th); + }), + + CHECK("parse ClientHello stays incomplete when fragments leave a gap", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto message = client_hello_bare_bytes(); + const size_t gap_start = message.size() / 3; + const size_t gap_end = 2 * message.size() / 3; + result.require("gap smaller than message", gap_start < gap_end && gap_end < message.size()); + result.require("gap is not empty", gap_start + 1 < gap_end); + + // fragment covering [0, gap_start) and [gap_end, message.size()), leaving + // [gap_start, gap_end) unfilled + const auto before_gap = std::span{message}.first(gap_start); + const auto after_gap = std::span{message}.subspan(gap_end); + + result.require( + "successful ingestion 1", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, 0, before_gap))) == CopyDataResult::Consumed); + result.require( + "successful ingestion 2", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, gap_end, after_gap))) == CopyDataResult::Consumed); + + result.test_opt_is_null("message never completes due to the gap", hl->next_message(default_policy, th)); + }), + + CHECK("parse ClientHello detects an invalid oversized fragment", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto message = client_hello_bare_bytes(); + + // a fragment whose offset + length overflows the declared total message length + const std::vector bogus_payload(50, 0x41); + result.test_throws("bogus data is rejected", [&] { + std::ignore = hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, message.size() - 1, bogus_payload))); + }); + result.test_opt_is_null("bogus fragment does not complete the message", + hl->next_message(default_policy, th)); + + // sending all the valid fragments afterwards should still reassemble correctly + const auto pieces = split_into_pieces(message, equal_sizes(message.size(), 3)); + result.require("at least two pieces", pieces.size() >= 2); + result.require("successful ingestion", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, pieces[0].offset, pieces[0].bytes))) == + CopyDataResult::Consumed); + + // fragments whose header values disagree with the pending + // reassembly (total length, message type) are rejected + result.test_throws("inconsistent total message length is rejected", [&] { + std::ignore = + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size() + 1, msg_seq, pieces[1].offset, pieces[1].bytes))); + }); + result.test_throws("inconsistent message type is rejected", [&] { + std::ignore = hl->copy_data( + default_policy, + handshake_record(dtls_marshall_fragment( + TLS::Handshake_Type::Finished, message.size(), msg_seq, pieces[1].offset, pieces[1].bytes))); + }); + + // fragments of one message must not span multiple record epochs + result.test_throws("fragments spanning multiple epochs are rejected", [&] { + std::ignore = hl->copy_data( + default_policy, + handshake_record( + dtls_marshall_fragment(type, message.size(), msg_seq, pieces[1].offset, pieces[1].bytes), + epoch_appdata_0)); + }); + + // the pending reassembly is unharmed by the rejected fragments + for(size_t i = 1; i < pieces.size(); ++i) { + result.require("successful ingestion", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, pieces[i].offset, pieces[i].bytes))) == + CopyDataResult::Consumed); + } + + auto msg = hl->next_message(default_policy, th); + + verify_client_hello(result, msg, th); + }), + + CHECK("parse ClientHello detects incoming garbage data with invalid message type", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto message = client_hello_bare_bytes(); + + // This resembles a fragment with a message length of 0 (which is allowed), + // but the message type is invalid (0x00 does not exist in (D)TLS 1.3). The + // message should be rejected because of the invalid message type, but the + // rest of the fragment is in fact valid. + const std::array garbage{0x42 /* msg type: 0x42 does not exist! */}; + result.test_throws("invalid message type is detected", + [&] { std::ignore = hl->copy_data(default_policy, handshake_record(garbage)); }); + result.test_opt_is_null("bogus fragment does not complete the message", + hl->next_message(default_policy, th)); + + // sending all the valid fragments afterwards should still reassemble correctly + const auto pieces = split_into_pieces(message, equal_sizes(message.size(), 3)); + for(const auto& piece : pieces) { + result.test_enum_eq("successful ingestion", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, piece.offset, piece.bytes))), + CopyDataResult::Consumed); + } + + verify_client_hello(result, hl->next_message(default_policy, th), th); + }), + + CHECK("parse ClientHello detects incoming garbage data with valid message type", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + // A fragment whose message type is correct (ClientHello) but that + // declares a zero-length message. copy_data() happily buffers it + // (an empty message is immediately "complete"), and the bogus + // content is only detected when parsing the message. + // + // TODO: The bogus message should ideally be detected and rejected + // already in copy_data(). Also, the unparsable message + // remains in the reassembly buffer after the failed parse, + // i.e. the handshake layer is wedged from this point on. + const std::array garbage{0x01 /* msg type: 0x01 - Client Hello! */}; + result.test_enum_eq("garbage is buffered like any other fragment", + hl->copy_data(default_policy, handshake_record(garbage)), + CopyDataResult::Consumed); + result.test_throws("bogus message is detected at parse time", + [&] { static_cast(hl->next_message(default_policy, th)); }); + }), + + CHECK("parse ClientHello detects incoming short garbage data", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto th = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto message = client_hello_bare_bytes(); + + // a fragment whose message type is correct but it is too short to be a valid message + const std::array garbage{0x01 /* msg type: 0x01 - Client Hello! */}; + result.test_throws("detects garbage", + [&] { static_cast(hl->copy_data(default_policy, handshake_record(garbage))); }); + result.test_opt_is_null("bogus fragment does not complete the message", + hl->next_message(default_policy, th)); + + // sending all the valid fragments afterwards should still reassemble correctly + const auto pieces = split_into_pieces(message, equal_sizes(message.size(), 3)); + for(const auto& piece : pieces) { + result.require("successful ingestion", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + type, message.size(), msg_seq, piece.offset, piece.bytes))) == + CopyDataResult::Consumed); + } + + verify_client_hello(result, hl->next_message(default_policy, th), th); + }), + + CHECK("Fragmentation round-trip", + [&](Test::Result& result) { + auto hl_client = make_handshake_layer(TLS::Connection_Side::Client); + auto hello = client_hello(); + + const auto message = client_hello_bare_bytes(); + const uint16_t fragment_size = static_cast(message.size() / 3); + + const auto fragments = + hl_client->fragment_message(hello.wire_type(), TLS::Handshake_Layer::serialize(hello), fragment_size); + result.test_is_true("fragmented", fragments.size() > 1); + + // feed the fragments back into a new handshake layer and check that the original message is reassembled + auto hl_server = make_handshake_layer(TLS::Connection_Side::Server); + auto th_server = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + for(const auto& fragment : fragments) { + result.require("successful ingestion", + hl_server->copy_data(default_policy, handshake_record(fragment.get())) == + CopyDataResult::Consumed); + } + + auto msg = hl_server->next_message(default_policy, th_server); + + verify_client_hello(result, msg, th_server); + }), + + CHECK("(Retransmitted) fragments of historic messages should be dropped", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Server); + auto transcript_hash = TLS::Transcript_Hash_State(TLS::TLS_Flavor::DTLS); + + const auto ch = client_hello_bare_bytes(); + + result.require("successful ingestion of seqno 0", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + TLS::Handshake_Type::ClientHello, ch.size(), 0 /* seqno */, 0, ch))) == + CopyDataResult::Consumed); + verify_client_hello(result, hl->next_message(default_policy, transcript_hash), transcript_hash); + + result.test_enum_eq( + "retransmission of Client Hello is dropped", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + TLS::Handshake_Type::ClientHello, ch.size(), 0 /* seqno */, 0, ch))), + CopyDataResult::DiscardedDuplicate); + result.test_opt_is_null("no more messages", hl->next_message(default_policy, transcript_hash)); + }), + }; +} + +std::vector post_handshake() { + const auto default_policy = TLS::Policy(); + + auto marshalled_key_update = [](uint16_t msg_seq, bool request_peer_update) { + const std::array body{static_cast(request_peer_update ? 0x01 : 0x00)}; + return dtls_marshall_fragment(TLS::Handshake_Type::KeyUpdate, body.size(), msg_seq, 0, body); + }; + + return { + CHECK("Key_Update messages are parsed", + [&](Test::Result& result) { + auto client = make_handshake_layer(TLS::Connection_Side::Client); + auto server = make_handshake_layer(TLS::Connection_Side::Server); + + // send a Key_Update through the fragmenting send path + const auto fragments = client->fragment_message(TLS::Handshake_Type::KeyUpdate, + TLS::Handshake_Layer::serialize(TLS::Key_Update(false)), + TLS::MAX_PLAINTEXT_SIZE); + result.test_sz_eq("Key_Update fits into a single fragment", fragments.size(), 1); + + result.test_enum_eq( + "successful ingestion", + server->copy_data(default_policy, handshake_record(fragments.front().get(), epoch_appdata_0)), + CopyDataResult::Consumed); + + auto msg = server->next_post_handshake_message(default_policy, epoch_appdata_0); + result.require("received something", msg.has_value()); + result.require("message is Key_Update", std::holds_alternative(msg.value())); + result.test_is_false("peer does not request reciprocation", + std::get(msg.value()).expects_reciprocation()); + + result.test_enum_eq( + "successful ingestion", + server->copy_data(default_policy, handshake_record(marshalled_key_update(1, true), epoch_appdata_0)), + CopyDataResult::Consumed); + auto msg2 = server->next_post_handshake_message(default_policy, epoch_appdata_0); + result.require("received something", msg2.has_value()); + result.require("message is Key_Update", std::holds_alternative(msg2.value())); + result.test_is_true("peer requests reciprocation", + std::get(msg2.value()).expects_reciprocation()); + }), + + CHECK("Post-handshake messages arriving on outdated epochs are rejected", + [&](Test::Result& result) { + auto hl = make_handshake_layer(TLS::Connection_Side::Client); + + // RFC 9147 Section 8 + // Due to loss and/or reordering, DTLS 1.3 implementations may + // receive a record with an older epoch than the current one + // [...]. They SHOULD attempt to process those records with + // that epoch [...] but MAY opt to discard such out-of-epoch + // records. + // + // Simulate a KeyUpdate overtaking a NewSessionTicket in flight: + // once the KeyUpdate is processed, the connection's current + // epoch has advanced, but the reordered ticket still arrives on + // the previous epoch and must be processed normally. + result.test_enum_eq( + "successful ingestion of KeyUpdate", + hl->copy_data(default_policy, + handshake_record(marshalled_key_update(0 /* seqno */, false), epoch_appdata_0)), + CopyDataResult::Consumed); + result.require("received KeyUpdate", + hl->next_post_handshake_message(default_policy, epoch_appdata_0).has_value()); + + const auto nst = new_session_ticket_bare_bytes(); + result.test_enum_eq( + "successful ingestion on the outdated epoch", + hl->copy_data(default_policy, + handshake_record(dtls_marshall_fragment( + TLS::Handshake_Type::NewSessionTicket, nst.size(), 1 /* seqno */, 0, nst))), + CopyDataResult::Consumed); + + result.test_throws("NST was protected with a now-outdated epoch", [&] { + hl->next_post_handshake_message(default_policy, epoch_appdata_1); + }); + }), + }; +} + +} // namespace + +BOTAN_REGISTER_TEST_FN("tls", "dtls_handshake_layer_13_basic", basic); +BOTAN_REGISTER_TEST_FN("tls", "dtls_handshake_layer_13_fragmentation", fragmentation); +BOTAN_REGISTER_TEST_FN("tls", "dtls_handshake_layer_13_post_handshake", post_handshake); + +} // namespace Botan_Tests + +#endif diff --git a/src/tests/test_tls_dtls13_record_layer.cpp b/src/tests/test_tls_dtls13_record_layer.cpp new file mode 100644 index 00000000000..559374ff05c --- /dev/null +++ b/src/tests/test_tls_dtls13_record_layer.cpp @@ -0,0 +1,1837 @@ +/* +* (C) 2026 Jack Lloyd +* (C) 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include "tests.h" + +#if defined(BOTAN_HAS_DTLS_13) + + #include + #include + + #include + #include + #include + #include + #include + #include + #include + #include + +namespace TLS = Botan::TLS; + +namespace Botan_Tests { + +namespace { + +constexpr auto epoch_appdata_0 = TLS::EpochNumber::create(3); + +auto create_policy(std::optional minimum_record_size = {}, + std::optional maximum_queued_acknowledgements = {}, + std::optional maximum_deprotection_failures = {}) { + class Test_Policy : public Botan::TLS::Policy { + public: + Test_Policy(std::optional minimum_record_size, + std::optional maximum_queued_acknowledgements, + std::optional maximum_deprotection_failures) : + m_minimum_record_size(minimum_record_size), + m_maximum_queued_acknowledgements(maximum_queued_acknowledgements), + m_maximum_deprotection_failures(maximum_deprotection_failures) {} + + size_t record_padding_bytes(size_t plaintext_bytes) const override { + return plaintext_bytes < m_minimum_record_size ? *m_minimum_record_size - plaintext_bytes : 0; + } + + size_t dtls_maximum_queued_acknowledgements() const override { + return m_maximum_queued_acknowledgements.value_or(Policy::dtls_maximum_queued_acknowledgements()); + } + + size_t dtls_maximum_deprotection_failures() const override { + return m_maximum_deprotection_failures.value_or(Policy::dtls_maximum_deprotection_failures()); + } + + private: + std::optional m_minimum_record_size; + std::optional m_maximum_queued_acknowledgements; + std::optional m_maximum_deprotection_failures; + }; + + return std::make_shared( + minimum_record_size, maximum_queued_acknowledgements, maximum_deprotection_failures); +} + +std::unique_ptr make_cipher_state(TLS::Connection_Side side, + std::string_view suite = "AES_128_GCM_SHA256") { + const auto cipher = TLS::Ciphersuite::from_name(suite).value(); + return TLS::Cipher_State::init_with_server_hello( + side, TLS::TLS_Flavor::DTLS, Botan::secure_vector(32, 0x00), cipher, std::vector(32, 0x00), {}); +} + +void advance_to_application_traffic(TLS::Cipher_State& cs) { + const std::vector dummy_transcript_hash(32, 0x42); + cs.advance_with_server_finished(dummy_transcript_hash); + cs.advance_with_client_finished(dummy_transcript_hash); +} + +TLS::PackedHandshakeMessageFragments packed(std::span fragment) { + return TLS::PackedHandshakeMessageFragments(std::vector(fragment.begin(), fragment.end())); +} + +Botan::secure_vector prepare_record(TLS::DTLS_Record_Layer& rl, + const TLS::Policy& policy, + TLS::Record_Type type, + std::span payload, + TLS::Cipher_State* cipher_state = nullptr) { + Botan::secure_vector out; + rl.prepare_record(type, payload, policy, cipher_state, out); + return out; +} + +Botan::secure_vector prepare_handshake_record(TLS::DTLS_Record_Layer& rl, + const TLS::Policy& policy, + std::span fragment, + TLS::Cipher_State* cipher_state = nullptr) { + Botan::secure_vector out; + rl.prepare_handshake_record(packed(fragment), out, policy, cipher_state); + return out; +} + +auto parse_header(std::span bytes, std::optional cid_length) { + Botan::BufferSlicer bs(bytes); + return TLS::UnifiedHeader_DTLS::parse(bs, cid_length); +} + +std::vector read_clienthello_record() { + const auto client_hello_record = Botan::hex_decode( // from wolfssl + "16 fe fd 00 00 00 00 00 00 00 00 01 fa 01 00 01 ee 00 00 00 00" + "00 00 01 ee fe fd 9a 71 88 3e 33 0e f5 ac f3 1a 3e 34 b6 28 59" + "cf b5 4b 25 14 e9 fd 7a 88 56 7b 3c 91 56 76 3a 4e 00 00 00 36" + "13 02 13 01 13 03 c0 2c c0 2b c0 30 c0 2f 00 9f 00 9e cc a9 cc" + "a8 cc aa c0 27 c0 23 c0 28 c0 24 c0 0a c0 09 c0 14 c0 13 00 6b" + "00 67 00 39 00 33 cc 14 cc 13 cc 15 01 00 01 8e 00 2b 00 03 02" + "fe fc 00 0d 00 1c 00 1a 06 03 05 03 04 03 08 06 08 0b 08 05 08" + "0a 08 04 08 09 06 01 05 01 04 01 03 01 00 0a 00 10 00 0e 11 ed" + "11 eb 00 19 00 18 00 17 00 15 01 00 00 16 00 00 00 33 01 4b 01" + "49 00 17 00 41 04 9d 51 3d c7 9b ad 20 a2 4d 54 f7 24 72 ea 25" + "df 33 0f 51 7e c6 69 34 db 6b 20 52 94 74 ee 2b 4e 3d ad 4b 5d" + "d6 83 df 82 13 90 be f2 b6 55 67 87 cd a4 30 37 62 e0 6e 45 31" + "04 1a 5e d0 56 17 97 01 00 01 00 13 9d f5 5b 77 eb 78 86 b2 87" + "e4 f7 28 7b 09 62 99 ca 70 30 0a 7a 5d 1f 1a fd 78 fd 6a 7b 49" + "49 ac 66 49 62 48 a7 bc 05 37 cd f0 c3 95 f4 f1 e5 d1 07 dc 8a" + "48 4a 2a 73 c2 0f 2d 29 66 8f e2 33 69 79 f9 df c8 91 99 20 e4" + "dc 6d 56 e4 a9 34 bd f5 bc d8 05 b6 f7 de 6c 0b 29 81 7b 60 c5" + "58 2d 76 7c 4b d9 59 84 65 bb 19 90 a4 13 e4 69 db 5d 2b 7d 03" + "c3 ef f1 fe 1d f6 3e 9b af fd 69 48 31 74 1a 54 6b 43 05 1c ae" + "08 90 6d 4e 8b b4 86 e9 90 58 1e bb 34 06 9b 31 eb 11 18 4c aa" + "84 14 a0 04 0f 71 1b 09 93 c2 b2 ca 0e c1 53 2b 9e 2c 5e 24 92" + "73 09 72 54 82 40 14 a8 48 9c 9e ab 80 31 36 2c b1 5d fd b7 c1" + "65 bb b6 c4 e1 9f 0c 53 5c 8d 08 95 28 9c 7a 69 b4 2c 4e 5a b0" + "b4 9f a1 b3 cd d9 ff 37 78 2d 1f cf ff 4d 76 32 6c d5 fc eb 1a" + "2c e2 9e 04 85 d3 af 10 3c 4c fa b6 6e 47 66"); + + const auto policy = create_policy(); + + return { + CHECK("Parse ClientHello", + [&](Test::Result& result) { + TLS::DTLS_Record_Layer rl{*policy}; + result.test_is_true("ingest client hello", rl.copy_data(client_hello_record, false)); + + const auto read = rl.next_record(); + result.require("received something", !std::holds_alternative(read)); + const auto record = std::get(read); + + result.test_enum_eq("received handshake", record.type, TLS::Record_Type::Handshake); + result.test_u64_eq("sequence_number is 0", record.sequence_number.value(), 0); + result.test_is_true("epoch is 0", record.epoch->is_unprotected()); + result.test_bin_eq("received handshake message", + record.payload, + std::span{client_hello_record}.subspan(Botan::TLS::Size_Limits::DTLS_HEADER_SIZE)); + + result.test_is_true("no more records", std::holds_alternative(rl.next_record())); + }), + + CHECK("Reading records partially fails", + [&](Test::Result& result) { + // DTLS records must not span datagrams, but copy_data + // in DTLS assumes to be called on a full datagram. + TLS::DTLS_Record_Layer rl{*policy}; + + // Not enough to read record header (13 bytes) + result.test_is_false("partial header is discarded", + rl.copy_data(std::span{client_hello_record}.first(10), false)); + result.test_is_true("nothing to read", std::holds_alternative(rl.next_record())); + + // Full header provided, still just a partial datagram + result.test_is_false("partial payload is discarded", + rl.copy_data(std::span{client_hello_record}.first(13), false)); + result.test_is_true("nothing to read", std::holds_alternative(rl.next_record())); + + // Syntactically invalid datagrams are silently discarded even + // when a cryptographic association exists (RFC 9147 4.5.2). + result.test_is_false("partial datagram is discarded with association", + rl.copy_data(std::span{client_hello_record}.first(13), true)); + result.test_is_true("nothing to read", std::holds_alternative(rl.next_record())); + }), + + CHECK("legacy_record_version", + [&](Test::Result& result) { + // Semantically invalid datagrams abort the connection attempt + // (throw) as long as no cryptographic association exists, but + // are silently discarded once one was established + auto bad_record = client_hello_record; + bad_record[1] = 0x03; // Invalid version + bad_record[2] = 0x03; + + TLS::DTLS_Record_Layer rl{*policy}; + result.test_throws("bad record version throws without association", + [&] { rl.copy_data(bad_record, false); }); + result.test_is_false("bad record version is discarded with association", rl.copy_data(bad_record, true)); + result.test_is_true("nothing to read", std::holds_alternative(rl.next_record())); + + auto dtls10_record = client_hello_record; + dtls10_record[1] = 0xFE; // Only valid for initial ClientHello + dtls10_record[2] = 0xFF; + TLS::DTLS_Record_Layer rl2{*policy}; + result.test_is_true("ingest dtls10 record", rl2.copy_data(dtls10_record, false)); + const auto record = std::get(rl2.next_record()); + result.test_enum_eq("received handshake", record.type, TLS::Record_Type::Handshake); + + rl2.disable_receiving_compat_mode(); + + // RFC 9147 Section 4. + // legacy_record_version: This value MUST be set to {254, 253} for all + // records other than the initial ClientHello (i.e., one not generated + // after a HelloRetryRequest), where it may also be {254, 255} for + // compatibility purposes. It MUST be ignored for all purposes. + // + // I.e., we also must not reject such a record. It may even come from an + // off-path attacker in DTLS. + result.test_no_throw("dtls10 record is not early-rejected in strict mode", + [&] { rl2.copy_data(dtls10_record, false); }); + }), + + CHECK("epoch 0 round-trip with duplicate rejection", + [&](Test::Result& result) { + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + const std::array, 2> payloads = {Botan::hex_decode("deadbeef"), + Botan::hex_decode("beefdead")}; + + for(size_t i = 0; i < payloads.size(); i++) { + // Two round-trips to test sequence_number increment + const auto wire = prepare_handshake_record(rl_out, *policy, payloads[i]); + result.test_u64_eq( + "write sequence number incremented", rl_out.epoch0_sequence_numbers()->write, i + 1); + + result.require("ingestion is successful", rl_in.copy_data(wire, false)); + const auto record = std::get(rl_in.next_record()); + + // Test that the created record can be read + result.test_enum_eq("type is Handshake", record.type, TLS::Record_Type::Handshake); + result.test_u64_eq("sequence_number is right", record.sequence_number.value(), i); + result.test_is_true("epoch is 0", record.epoch->is_unprotected()); + result.test_bin_eq("payload matches", record.payload, payloads[i]); + + // Receiving the very same record again must not deliver it twice + result.test_is_true("ingest duplicate record", rl_in.copy_data(wire, false)); + result.test_is_true("duplicate record is discarded", + std::holds_alternative(rl_in.next_record())); + } + }), + + CHECK( + "records from a partially invalid datagram are dropped entirely", + [&](Test::Result& result) { + // Records are committed to the read buffer only once the + // entire datagram was parsed successfully + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + const auto valid_record = prepare_handshake_record(rl_out, *policy, Botan::hex_decode("deadbeef")); + + // A truncated record header trails the valid record, rendering + // the entire datagram syntactically invalid. + const auto datagram = Botan::concat>(valid_record, std::array{0x16, 0xFE}); + result.test_is_false("partially invalid datagram is discarded", rl_in.copy_data(datagram, false)); + result.test_is_true("valid record was not committed either", + std::holds_alternative(rl_in.next_record())); + }), + }; +} + +std::vector protected_records() { + const auto policy = create_policy(); + + return { + CHECK("basic round-trip", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + advance_to_application_traffic(*cs_client); + advance_to_application_traffic(*cs_server); + + const auto to_be_protected_payload = Botan::hex_decode("efbeadde"); + + const auto record = prepare_record( + rl_out, *policy, TLS::Record_Type::ApplicationData, to_be_protected_payload, cs_client.get()); + + result.test_u8_eq("epoch encoded as 001xxxEE", record[0] & 0xE3, 0x23); + + result.require("ingestion is successful", rl_in.copy_data(record, true)); + const auto deprotected = std::get(rl_in.next_record(cs_server.get())); + result.test_bin_eq("deprotected record matches payload", deprotected.payload, to_be_protected_payload); + result.test_enum_eq("record type", deprotected.type, TLS::Record_Type::ApplicationData); + result.test_u64_eq("record sequence_number", deprotected.sequence_number.value(), uint64_t{0}); + result.test_is_true("record epoch is application traffic", + deprotected.epoch->application_traffic_index() == 0); + }), + + CHECK("read protected record", + [&](Test::Result& result) { + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + TLS::DTLS_Record_Layer rl_server{*policy}; + + // Generated by Botan via prepare_record + const auto wire = Botan::hex_decode( + "2e 76 cf 00 1b 9a c7 72 ae 54 cb f8 cc 7b 09 72" + "9d 4a 6f 78 89 c9 3b ff 4e 62 a5 3f 4f 34 c4 fb"); + result.require("parsing success", rl_server.copy_data(wire, true)); + + const auto records = rl_server.next_record(cs_server.get()); + result.require("produced a record", !std::holds_alternative(records)); + + const auto& record = std::get(records); + result.test_bin_eq("payload matches", record.payload, "68656c6c6f2064746c73"); + result.test_enum_eq("type is Handshake", record.type, TLS::Record_Type::Handshake); + }), + + CHECK("reading protected record without key state should drop the record", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + TLS::DTLS_Record_Layer rl_client{*policy}; + TLS::DTLS_Record_Layer rl_server{*policy}; + + const auto wire = prepare_handshake_record( + rl_client, *policy, Botan::hex_decode("68656c6c6f2064746c73"), cs_client.get()); + result.require("parsing success", rl_server.copy_data(wire, false)); + + const auto records = rl_server.next_record(nullptr); + result.require("produced no record", std::holds_alternative(records)); + }), + + CHECK("read multiple protected records from one datagram", + [&](Test::Result& result) { + const auto cs_writer = make_cipher_state(TLS::Connection_Side::Server); + const auto cs_reader = make_cipher_state(TLS::Connection_Side::Client); + advance_to_application_traffic(*cs_writer); + advance_to_application_traffic(*cs_reader); + + TLS::DTLS_Record_Layer rl_writer{*policy}; + TLS::DTLS_Record_Layer rl_reader{*policy}; + + const auto payload1 = Botan::hex_decode("7365727665722068656c6c6f"); + const auto payload2 = Botan::hex_decode("617070207061796c6f6164"); + + // A (post-handshake) Handshake record followed by an + // ApplicationData record, coalesced into a single datagram. + const auto record1 = prepare_handshake_record(rl_writer, *policy, payload1, cs_writer.get()); + const auto record2 = + prepare_record(rl_writer, *policy, TLS::Record_Type::ApplicationData, payload2, cs_writer.get()); + const auto wire = Botan::concat>(record1, record2); + + result.require("parsing success", rl_reader.copy_data(wire, true)); + + const auto read1 = rl_reader.next_record(cs_reader.get()); + result.require("produced a record", !std::holds_alternative(read1)); + + const auto& r1 = std::get(read1); + result.test_bin_eq("payload matches", r1.payload, payload1); + result.test_enum_eq("type is Handshake", r1.type, TLS::Record_Type::Handshake); + + const auto read2 = rl_reader.next_record(cs_reader.get()); + result.require("produced another record", !std::holds_alternative(read2)); + + const auto& r2 = std::get(read2); + result.test_bin_eq("payload matches", r2.payload, payload2); + result.test_enum_eq("type is ApplicationData", r2.type, TLS::Record_Type::ApplicationData); + + result.test_is_true("no more records", + std::holds_alternative(rl_reader.next_record(cs_reader.get()))); + }), + + CHECK("tampered ciphertext is dropped", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_client{*policy}; + TLS::DTLS_Record_Layer rl_server{*policy}; + + auto wire = prepare_handshake_record( + rl_client, *policy, Botan::hex_decode("68656c6c6f2064746c73"), cs_client.get()); + wire.back() ^= 0x40; // flip a bit in the last ciphertext byte + + result.test_is_true("datagram is accepted", rl_server.copy_data(wire, true)); + result.test_sz_eq( + "No records", std::get(rl_server.next_record(cs_server.get())), 0); + result.test_u64_eq( + "failed deprotection is counted", cs_server->current_read_epoch_deprotection_failures(), 1); + }), + + CHECK("exceeding the deprotection failure limit closes the connection", + [&](Test::Result& result) { + constexpr size_t deprotection_failure_limit = 2; + const auto strict_policy = create_policy({}, {}, deprotection_failure_limit); + + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + advance_to_application_traffic(*cs_client); + advance_to_application_traffic(*cs_server); + + TLS::DTLS_Record_Layer rl_out{*strict_policy}; + TLS::DTLS_Record_Layer rl_in{*strict_policy}; + + auto wire = prepare_record(rl_out, + *strict_policy, + TLS::Record_Type::ApplicationData, + Botan::hex_decode("deadbeef"), + cs_client.get()); + wire.back() ^= 0x01; + + result.require("ingest tampered record", rl_in.copy_data(wire, true)); + result.test_is_true("first authentication failure is silently discarded", + std::holds_alternative(rl_in.next_record(cs_server.get()))); + result.test_u64_eq( + "one deprotection failure counted", cs_server->current_read_epoch_deprotection_failures(), 1); + + result.require("ingest second tampered record", rl_in.copy_data(wire, true)); + result.test_is_true("second authentication failure is silently discarded", + std::holds_alternative(rl_in.next_record(cs_server.get()))); + result.test_u64_eq( + "two deprotection failures counted", cs_server->current_read_epoch_deprotection_failures(), 2); + + result.require("ingest third tampered record", rl_in.copy_data(wire, true)); + result.test_throws("deprotection failure limit exceeded", + "Too many deprotection failures in current read epoch", + [&] { rl_in.next_record(cs_server.get()); }); + }), + + CHECK("protected ChangeCipherSpec (inner type) is rejected", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + // The record layer refuses to emit CCS records for RFC compliance, + // so we create a protected CCS via the cipher state directly. + Botan::secure_vector wire; + TLS::as_dtls_cipher_state(cs_client.get()) + ->protect_record(TLS::Record_Type::ChangeCipherSpec, Botan::hex_decode("01"), 0, wire); + + TLS::DTLS_Record_Layer rl{*policy}; + result.test_is_true("ingest doesn't reject protected datagram", rl.copy_data(wire, true)); + result.test_throws("No records", + "Deprotected DTLS record had unexpected content type: 20", + [&] { rl.next_record(cs_server.get()); }); + }), + + CHECK("application data at the handshake epoch is rejected", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + // Note that the record layer currently produces such a record + // without complaint; the peer's cipher state rejects it. + const auto record = prepare_record( + rl_out, *policy, TLS::Record_Type::ApplicationData, Botan::hex_decode("deadbeef"), cs_client.get()); + + result.require("ingestion is successful", rl_in.copy_data(record, true)); + result.test_throws("application data before handshake completion is rejected", + "Application data received before handshake completion", + [&] { rl_in.next_record(cs_server.get()); }); + }), + + CHECK("application data replayed at the handshake epoch is rejected after handshake completion", + [&](Test::Result& result) { + // Even with application traffic keys in place, application + // data must not arrive at the handshake epoch + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + const auto record = prepare_record( + rl_out, *policy, TLS::Record_Type::ApplicationData, Botan::hex_decode("deadbeef"), cs_client.get()); + + // The recipient has completed the handshake in the meantime + // and holds application traffic secrets. + advance_to_application_traffic(*cs_server); + + result.require("ingestion is successful", rl_in.copy_data(record, true)); + result.test_throws("application data at the handshake epoch is rejected", + "Can't interleave application and handshake data", + [&] { rl_in.next_record(cs_server.get()); }); + }), + + CHECK("unprotected and protected records in a single datagram", + [&](Test::Result& result) { + // This simulates the situation where a datagram contains both + // unprotected and protected records. The record layer should be + // able to read both sequentially. + // + // Such a situation can occur in DTLS 1.3 for the first server + // flight, where the server sends an unprotected ServerHello + // followed by a protected EncryptedExtensions record... + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + const std::array, 2> payloads = { + Botan::hex_decode("deadbeef"), + Botan::hex_decode("beefdead"), + }; + + // A single datagram that contains an unprotected Handshake + // record followed by a protected (handshake traffic epoch) + // Handshake record. + const auto unprotected_record = prepare_handshake_record(rl_out, *policy, payloads[0]); + const auto protected_record = prepare_handshake_record(rl_out, *policy, payloads[1], cs_server.get()); + const auto wire = Botan::concat>(unprotected_record, protected_record); + + result.require("reading hybrid datagram", rl_in.copy_data(wire, true)); + const auto unprotected = rl_in.next_record(nullptr); + result.test_is_true("expect getting a record", !std::holds_alternative(unprotected)); + const auto record1 = std::get(unprotected); + result.test_enum_eq("type is Handshake", record1.type, TLS::Record_Type::Handshake); + result.test_bin_eq("payload matches", record1.payload, payloads[0]); + + const auto was_protected = rl_in.next_record(cs_client.get()); + result.test_is_true("expect getting a record", !std::holds_alternative(was_protected)); + const auto record2 = std::get(was_protected); + result.test_enum_eq("type is Handshake", record2.type, TLS::Record_Type::Handshake); + result.test_is_true("epoch is handshake traffic", record2.epoch->is_handshake_traffic()); + result.test_bin_eq("payload matches", record2.payload, payloads[1]); + + result.test_is_true("no more records", + std::holds_alternative(rl_in.next_record(cs_client.get()))); + }), + + CHECK("duplicated and too-old protected records are rejected", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + advance_to_application_traffic(*cs_client); + advance_to_application_traffic(*cs_server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + const auto payload = Botan::hex_decode("deadbeef"); + + const auto first_record = + prepare_record(rl_out, *policy, TLS::Record_Type::ApplicationData, payload, cs_client.get()); + + result.require("ingest first record", rl_in.copy_data(first_record, true)); + result.test_is_true("first record is delivered", + !std::holds_alternative(rl_in.next_record(cs_server.get()))); + + // Receiving the very same record again must not deliver it twice. + // The duplicate deprotects successfully but is then rejected + // by the replay window (RFC 9147 Section 4.5.1). + result.test_is_true("ingest duplicate record", rl_in.copy_data(first_record, true)); + result.test_is_true("duplicate record is discarded", + std::holds_alternative(rl_in.next_record(cs_server.get()))); + + // Advance the replay window beyond the first record's sequence number + for(uint64_t i = 0; i < TLS::Replay_Window_13::window_size; ++i) { + const auto record = + prepare_record(rl_out, *policy, TLS::Record_Type::ApplicationData, payload, cs_client.get()); + result.require("ingest record", rl_in.copy_data(record, true)); + result.require("record is delivered", + !std::holds_alternative(rl_in.next_record(cs_server.get()))); + } + + // The first record's sequence number fell off the left edge of the window + result.test_is_true("ingest too-old record", rl_in.copy_data(first_record, true)); + result.test_is_true("too-old record is discarded", + std::holds_alternative(rl_in.next_record(cs_server.get()))); + + // The record layer is still functional afterwards + const auto fresh_record = + prepare_record(rl_out, *policy, TLS::Record_Type::ApplicationData, payload, cs_client.get()); + result.require("ingest fresh record", rl_in.copy_data(fresh_record, true)); + const auto read = rl_in.next_record(cs_server.get()); + result.require("fresh record is delivered", !std::holds_alternative(read)); + result.test_bin_eq("payload matches", std::get(read).payload, payload); + }), + + CHECK( + "replay windows are tracked per epoch", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + const auto payload = Botan::hex_decode("deadbeef"); + + // Sequence number 0 in the handshake traffic epoch (application + // data is not allowed, yet, hence a handshake-typed record) + const auto handshake_record = prepare_handshake_record(rl_out, *policy, payload, cs_client.get()); + result.require("ingest handshake epoch record", rl_in.copy_data(handshake_record, true)); + const auto read1 = rl_in.next_record(cs_server.get()); + result.require("handshake epoch record is delivered", !std::holds_alternative(read1)); + result.test_is_true("epoch is handshake traffic", + std::get(read1).epoch->is_handshake_traffic()); + + // Advance both cipher states to the application traffic epoch + advance_to_application_traffic(*cs_client); + advance_to_application_traffic(*cs_server); + + // Sequence number 0 in the application traffic epoch must be + // accepted, because replay state is tracked per epoch... + const auto app_record = + prepare_record(rl_out, *policy, TLS::Record_Type::ApplicationData, payload, cs_client.get()); + result.require("ingest application epoch record", rl_in.copy_data(app_record, true)); + const auto read2 = rl_in.next_record(cs_server.get()); + result.require("application epoch record is delivered", !std::holds_alternative(read2)); + result.test_is_true("epoch is application traffic", + std::get(read2).epoch->application_traffic_index() == 0); + result.test_u64_eq( + "sequence number is 0", std::get(read2).sequence_number.value(), 0); + + // ... while a duplicate in that epoch is still rejected. + result.require("ingest duplicate application epoch record", rl_in.copy_data(app_record, true)); + result.test_is_true("duplicate is discarded", + std::holds_alternative(rl_in.next_record(cs_server.get()))); + }), + + CHECK("pruning replay windows only releases the state of older epochs", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + const auto payload = Botan::hex_decode("deadbeef"); + + const auto delivers = [&](std::span record) { + result.require("ingest record", rl_in.copy_data(record, true)); + return !std::holds_alternative(rl_in.next_record(cs_server.get())); + }; + + // One record in the handshake traffic epoch... + const auto handshake_record = prepare_handshake_record(rl_out, *policy, payload, cs_client.get()); + result.require("handshake epoch record is delivered", delivers(handshake_record)); + + // ... and one in the application traffic epoch + advance_to_application_traffic(*cs_client); + advance_to_application_traffic(*cs_server); + const auto app_record = + prepare_record(rl_out, *policy, TLS::Record_Type::ApplicationData, payload, cs_client.get()); + result.require("application epoch record is delivered", delivers(app_record)); + + result.test_is_false("handshake epoch record is a replay", delivers(handshake_record)); + result.test_is_false("application epoch record is a replay", delivers(app_record)); + + // The replay window of the handshake epoch is released. The replay state of the + // application epoch is not affected. Note that the cipher state is not involved + // here, it still holds the keys of the handshake epoch. + rl_in.prune_replay_windows_older_than(epoch_appdata_0); + + result.test_is_false("application epoch record is still a replay", delivers(app_record)); + result.test_is_true("handshake epoch record is not remembered anymore", delivers(handshake_record)); + result.test_is_false("handshake epoch record is a replay again", delivers(handshake_record)); + + // Pruning with an epoch that is not newer than any tracked one has no effect + rl_in.prune_replay_windows_older_than(TLS::EpochNumber::unprotected()); + result.test_is_false("application epoch record is a replay after no-op pruning", delivers(app_record)); + result.test_is_false("handshake epoch record is a replay after no-op pruning", + delivers(handshake_record)); + }), + + CHECK("plaintext records are discarded once a cryptographic association exists", + [&](Test::Result& result) { + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + const auto plaintext_record = prepare_handshake_record(rl_out, *policy, Botan::hex_decode("deadbeef")); + + // RFC 9147 4.2.1: Implementations SHOULD discard records from + // earlier epochs. Once the cipher state reads in the handshake + // traffic epoch, plaintext (epoch 0) records are dropped. + result.require("ingest plaintext record", rl_in.copy_data(plaintext_record, true)); + result.test_is_true("plaintext record is discarded", + std::holds_alternative(rl_in.next_record(cs_server.get()))); + + // The same record is delivered when read without a cipher state. + TLS::DTLS_Record_Layer rl_in2{*policy}; + result.require("ingest plaintext record", rl_in2.copy_data(plaintext_record, false)); + result.test_is_true("plaintext record is delivered", + !std::holds_alternative(rl_in2.next_record(nullptr))); + }), + + CHECK("plaintext ACK records are tolerated until the application traffic epoch", + [&](Test::Result& result) { + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + const auto plaintext_ack = + prepare_record(rl_out, *policy, TLS::Record_Type::ACK, Botan::hex_decode("deadbeef")); + + // RFC 9147 7: ACKs are sent at an epoch equal to or higher than + // the acknowledged record's, so epoch 0 ACKs must remain + // acceptable while the handshake is in progress... + result.require("ingest plaintext ACK", rl_in.copy_data(plaintext_ack, true)); + const auto read = rl_in.next_record(cs_server.get()); + result.require("plaintext ACK is delivered at the handshake epoch", + !std::holds_alternative(read)); + result.test_enum_eq("record type is ACK", std::get(read).type, TLS::Record_Type::ACK); + + // ... but are discarded like any other plaintext record once + // the application traffic epoch is reached. + advance_to_application_traffic(*cs_server); + + TLS::DTLS_Record_Layer rl_in2{*policy}; + result.require("ingest plaintext ACK again", rl_in2.copy_data(plaintext_ack, true)); + result.test_is_true("plaintext ACK is discarded at the application traffic epoch", + std::holds_alternative(rl_in2.next_record(cs_server.get()))); + }), + + CHECK("plaintext ACK records are discarded after successfully receiving a protected record", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + // Successfully deprotecting a protected record proves that the + // peer is able to send authenticated records. From that point + // on, plaintext ACK records must not be acted upon anymore and + // are discarded like any other plaintext record (RFC 9147 + // 4.2.1: records from earlier epochs are discarded). + const auto protected_record = + prepare_handshake_record(rl_out, *policy, Botan::hex_decode("deadbeef"), cs_client.get()); + result.require("ingest protected record", rl_in.copy_data(protected_record, true)); + const auto protected_read = rl_in.next_record(cs_server.get()); + result.require("protected record is delivered", + !std::holds_alternative(protected_read)); + + const auto plaintext_ack = + prepare_record(rl_out, *policy, TLS::Record_Type::ACK, Botan::hex_decode("deadbeef")); + result.require("ingest plaintext ACK", rl_in.copy_data(plaintext_ack, true)); + result.test_is_true("plaintext ACK is discarded after a protected record was received", + std::holds_alternative(rl_in.next_record(cs_server.get()))); + + // The same holds when the cryptographic association is torn + // down from the write direction (e.g. after sending a + // close_notify alert, which clears our write keys): the peer + // has already proven that it can send authenticated records, + // so plaintext ACKs must still be ignored. + cs_server->clear_write_keys(); + result.test_is_false("no cryptographic association after clearing the write keys", + cs_server->has_cryptographic_association()); + + result.require("ingest plaintext ACK without cryptographic association", + rl_in.copy_data(plaintext_ack, false)); + result.test_is_true("plaintext ACK is still discarded without a cryptographic association", + std::holds_alternative(rl_in.next_record(cs_server.get()))); + + // This also pins down copy_data() itself: a syntactically + // valid but semantically invalid plaintext record (epoch + // != 0) is discarded instead of tearing down the connection, + // although the caller reports that no cryptographic + // association exists anymore. + auto semantically_invalid_ack = plaintext_ack; + semantically_invalid_ack[3] = 0x00; // epoch high byte + semantically_invalid_ack[4] = 0x01; // epoch low byte -> epoch 1 + result.test_is_false( + "semantically invalid plaintext record is discarded without a cryptographic association", + rl_in.copy_data(semantically_invalid_ack, false)); + }), + + CHECK("a protected record without a length field consumes the rest of the datagram", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + const auto payload = Botan::hex_decode("deadbeef"); + const auto valid_record = prepare_handshake_record(rl_out, *policy, payload, cs_client.get()); + + // RFC 9147 Section 4.3: The final record in a datagram can + // omit the length field; it then consumes the entire rest of + // the datagram. (epoch_bits=2, no CID, short seq_no, no length) + const auto lengthless_record = Botan::concat>( + std::array{0b00100010, 0x2A}, std::vector(16, 0xAA) /* garbage "ciphertext" */); + + const auto datagram = Botan::concat>(valid_record, lengthless_record); + + // A framing error would have rejected the datagram right away, + // taking the valid record down with it. + result.test_is_true("datagram with length-less final record is accepted", + rl_in.copy_data(datagram, true)); + + const auto read = rl_in.next_record(cs_server.get()); + result.require("record preceding the length-less one is delivered", + !std::holds_alternative(read)); + result.test_bin_eq("payload matches", std::get(read).payload, payload); + + result.test_is_true("length-less record is dropped after failed deprotection", + std::holds_alternative(rl_in.next_record(cs_server.get()))); + }), + + CHECK("protected record with too little ciphertext for deprotection is discarded", + [&](Test::Result& result) { + TLS::DTLS_Record_Layer rl_in{*policy}; + + // RFC 9147 4.2.3: unmasking the sequence number requires at + // least 16 bytes of ciphertext; shorter records are rejected + // as if they had failed deprotection. + // (epoch_bits=2, no CID, short seq_no, no length) + const auto wire = Botan::concat>(std::array{0b00100010, 0x2A}, + std::vector(15, 0xAA)); + + result.test_is_false("datagram is discarded", rl_in.copy_data(wire, true)); + result.test_is_true("nothing to read", + std::holds_alternative(rl_in.next_record(nullptr))); + }), + + CHECK("oversized protected record triggers record overflow", + [&](Test::Result& result) { + TLS::DTLS_Record_Layer rl{*policy}; + + // (epoch_bits=2, no CID, 16-bit seq_no, length present) + constexpr uint16_t advertised_length = 20000; + const auto wire = Botan::concat>( + std::array{0b00101110, + 0x00, + 0x00, + static_cast(advertised_length >> 8), + static_cast(advertised_length & 0xFF)}, + std::vector(advertised_length, 0xAA)); + + result.test_throws("record overflow is fatal without association", + "exceeds maximum size", + [&] { rl.copy_data(wire, false); }); + result.test_is_false("record overflow is discarded with association", rl.copy_data(wire, true)); + }), + + CHECK("record size limit depends on the protection epoch", + [&](Test::Result& result) { + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + TLS::DTLS_Record_Layer rl{*policy}; + + // Unprotected records use the 13-byte DTLSPlaintext header, + // protected records use the shorter unified header but incur + // AEAD expansion, so the payload limits differ per epoch. + const auto limit_unprotected = rl.record_payload_size_limit(*policy, nullptr); + const auto limit_epoch0 = + rl.record_payload_size_limit(*policy, cs_server.get(), TLS::EpochNumber::unprotected()); + const auto limit_protected = + rl.record_payload_size_limit(*policy, cs_server.get(), TLS::EpochNumber::handshake_traffic()); + + result.test_is_true("cipher state alone does not protect", limit_unprotected == limit_epoch0); + result.test_is_true("epoch 0 allows more payload than protected epochs", limit_epoch0 > limit_protected); + }), + + CHECK("negotiated record size limit is respected for protected records", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + advance_to_application_traffic(*cs_client); + advance_to_application_traffic(*cs_server); + + TLS::DTLS_Record_Layer rl{*policy}; + const size_t mtu = policy->dtls_default_mtu(); + + // Without negotiation, the MTU-derived limit applies to both + // protected and unprotected records. + const auto default_unprotected = rl.record_payload_size_limit(*policy, nullptr); + const auto default_epoch0 = + rl.record_payload_size_limit(*policy, cs_client.get(), TLS::EpochNumber::unprotected()); + const auto default_protected = + rl.record_payload_size_limit(*policy, cs_client.get(), TLS::EpochNumber::handshake_traffic()); + result.test_sz_eq("unprotected records are capped by the MTU", default_unprotected, mtu - 13); + result.test_sz_eq("unprotected epoch records are capped by the MTU", default_epoch0, mtu - 13); + // 5-byte unified header, 1-byte content type, 16-byte AEAD tag + result.test_sz_eq("protected records are capped by the MTU", default_protected, mtu - 22); + + // RFC 8449 4. + // When the "record_size_limit" extension is negotiated, an + // endpoint MUST NOT generate a protected record with plaintext + // that is larger than the RecordSizeLimit value it receives + // from its peer. Unprotected messages are not subject to this + // limit. + // + // The limit applies to the complete TLSInnerPlaintext, i.e. the + // payload plus the encrypted content type byte. With the smallest + // legal limit of 64, 63 payload bytes are left per record. + rl.set_record_size_limits(64 /* peer's limit */, TLS::MAX_PLAINTEXT_SIZE + 1 /* our limit */); + + const auto limited_protected = + rl.record_payload_size_limit(*policy, cs_client.get(), TLS::EpochNumber::handshake_traffic()); + result.test_sz_eq( + "protected records honor the negotiated limit incl. content type byte", limited_protected, 63); + result.test_sz_eq("unprotected records are not subject to the negotiated limit", + rl.record_payload_size_limit(*policy, nullptr), + default_unprotected); + result.test_sz_eq( + "unprotected epoch records are not subject to the negotiated limit", + rl.record_payload_size_limit(*policy, cs_client.get(), TLS::EpochNumber::unprotected()), + default_unprotected); + + // A mid-size limit leaves room for the content type byte but is + // still below the MTU-derived capacity. + rl.set_record_size_limits(1200 /* peer's limit */, TLS::MAX_PLAINTEXT_SIZE + 1 /* our limit */); + result.test_sz_eq( + "mid-size negotiated limit is honored", + rl.record_payload_size_limit(*policy, cs_client.get(), TLS::EpochNumber::handshake_traffic()), + 1199); + + // A limit at or above the MTU-derived capacity does not shrink + // the record payload limit any further. + rl.set_record_size_limits(TLS::MAX_PLAINTEXT_SIZE + 1 /* peer's limit */, + TLS::MAX_PLAINTEXT_SIZE + 1 /* our limit */); + result.test_sz_eq( + "negotiated limit above the MTU capacity keeps the MTU-derived limit", + rl.record_payload_size_limit(*policy, cs_client.get(), TLS::EpochNumber::handshake_traffic()), + default_protected); + }), + + CHECK("protected records honor the negotiated record size limit on the wire", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + advance_to_application_traffic(*cs_client); + advance_to_application_traffic(*cs_server); + + // The sender respects the 64-byte limit advertised by its peer; + // the receiver advertised a limit of its own that is irrelevant + // for the sender's records. + TLS::DTLS_Record_Layer rl_out{*policy}; + rl_out.set_record_size_limits(64 /* peer's limit */, TLS::MAX_PLAINTEXT_SIZE + 1 /* our limit */); + + const std::vector payload(63, 0x42); + const auto record = + prepare_record(rl_out, *policy, TLS::Record_Type::ApplicationData, payload, cs_client.get()); + + // 5-byte unified header + payload + 1-byte content type + 16-byte AEAD tag + result.test_sz_eq("record at the negotiated limit", record.size(), 5 + 63 + 1 + 16); + + // RFC 8449 4. (mirroring the TLS 1.3 record layer's check) + // ... an endpoint MUST NOT generate a protected record with + // plaintext that is larger than the RecordSizeLimit value it + // receives from its peer. + result.test_throws("payload beyond the negotiated limit is rejected", [&] { + const std::vector oversized_payload(64, 0x42); + prepare_record( + rl_out, *policy, TLS::Record_Type::ApplicationData, oversized_payload, cs_client.get()); + }); + + // The receiver accepts the record at the negotiated limit. + TLS::DTLS_Record_Layer rl_in{*policy}; + rl_in.set_record_size_limits(TLS::MAX_PLAINTEXT_SIZE + 1 /* peer's limit */, 64 /* our limit */); + result.require("ingestion is successful", rl_in.copy_data(record, true)); + const auto read = rl_in.next_record(cs_server.get()); + result.require("expect getting a record", !std::holds_alternative(read)); + const auto content = std::get(read); + result.test_bin_eq("payload matches", content.payload, payload); + }), + + CHECK("minimum record size is respected", + [&](Test::Result& result) { + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + advance_to_application_traffic(*cs_client); + advance_to_application_traffic(*cs_server); + + const uint16_t minimum_record_size = 1024; + + const auto policy_with_padding = create_policy(minimum_record_size); + TLS::DTLS_Record_Layer rl_out{*policy_with_padding}; + + const std::vector payload(1, 0x42); + const auto record = prepare_record( + rl_out, *policy_with_padding, TLS::Record_Type::ApplicationData, payload, cs_client.get()); + + // The lower bound does not include the unified record header + // which has a variable length. + const size_t expected_size_lower_bound = cs_client->encrypt_output_length(minimum_record_size); + result.test_sz_gte("produced wire bytes", record.size(), expected_size_lower_bound); + + // decryption + TLS::DTLS_Record_Layer rl_in{*policy_with_padding}; + result.require("ingestion is successful", rl_in.copy_data(record, true)); + const auto read = rl_in.next_record(cs_server.get()); + result.require("expect getting a record", !std::holds_alternative(read)); + const auto content = std::get(read); + result.test_enum_eq("type is ApplicationData", content.type, TLS::Record_Type::ApplicationData); + result.test_bin_eq("payload matches", content.payload, payload); + }), + + CHECK("round-trip with all relevant cipher suites", + [&](Test::Result& result) { + const auto go = [&](std::string_view suite) { + const auto suite_cs_client = make_cipher_state(TLS::Connection_Side::Client, suite); + const auto suite_cs_server = make_cipher_state(TLS::Connection_Side::Server, suite); + advance_to_application_traffic(*suite_cs_client); + advance_to_application_traffic(*suite_cs_server); + + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + // Short payload to make sure that certain cipher suites properly + // perform their implicit padding (See RFC 9147 4.2.3). + const auto payload = std::array{0x01, 0x02}; + const auto record = + prepare_record(rl_out, *policy, TLS::Record_Type::ApplicationData, payload, suite_cs_client.get()); + BOTAN_STATE_CHECK(record.size() >= 16); // minimum record size for all suites + + const bool read_success = rl_in.copy_data(record, true); + BOTAN_STATE_CHECK(read_success); + + const auto out_record = rl_in.next_record(suite_cs_server.get()); + BOTAN_STATE_CHECK(!std::holds_alternative(out_record)); + + BOTAN_ASSERT_NOMSG(std::get(out_record).payload.size() == + payload.size()); + BOTAN_ASSERT_NOMSG(std::get(out_record).payload[0] == payload[0]); + BOTAN_ASSERT_NOMSG(std::get(out_record).payload[1] == payload[1]); + }; + + const auto suites = std::array { + "AES_128_GCM_SHA256", "AES_256_GCM_SHA384", + #if defined(BOTAN_HAS_AEAD_CCM) + "AES_128_CCM_SHA256", "AES_128_CCM_8_SHA256", + #endif + #if defined(BOTAN_HAS_AEAD_CHACHA20_POLY1305) + "CHACHA20_POLY1305_SHA256", + #endif + }; + + for(const auto& suite : suites) { + try { + go(suite); + result.test_success("round-trip with " + std::string(suite) + " succeeded"); + } catch(const std::exception& e) { + result.test_failure("round-trip with " + std::string(suite) + " failed: " + e.what()); + } + } + }), + }; +} + +std::vector retransmission() { + const auto policy = create_policy(); + + // Reads epoch and sequence number off a DTLSPlaintext record header: + // type(1) || legacy_version(2) || epoch(2) || sequence_number(6) || length(2) + const auto plaintext_record_number = [](const TLS::MarshalledRecord& record) -> std::pair { + const uint64_t epoch = (static_cast(record[3]) << 8) | record[4]; + uint64_t seqno = 0; + for(size_t i = 0; i < 6; ++i) { + seqno = (seqno << 8) | record[5 + i]; + } + return {epoch, seqno}; + }; + + const auto payload1 = Botan::hex_decode("deadbeef"); + const auto payload2 = Botan::hex_decode("beefdead"); + const auto payload3 = Botan::hex_decode("beaddeef"); + + return { + CHECK("unacknowledged outgoing records are retransmitted until the flight state progresses", + [&](Test::Result& result) { + TLS::DTLS_Record_Layer rl{*policy}; + + // a flight of two unprotected handshake records (epoch 0) + Botan::secure_vector out1; + Botan::secure_vector out2; + const auto rn1 = rl.prepare_handshake_record(packed(payload1), out1, *policy, nullptr); + const auto rn2 = rl.prepare_handshake_record(packed(payload2), out2, *policy, nullptr); + result.test_is_true("first record in epoch 0", rn1.epoch.is_unprotected()); + result.test_u64_eq("first record sequence number", rn1.sequence_number, 0); + result.test_u64_eq("second record sequence number", rn2.sequence_number, 1); + + const std::array, 2> original = {out1, out2}; + + const auto retransmission = rl.prepare_unacknowledged_records(*policy, nullptr); + result.require("two records retransmitted", retransmission.size() == original.size()); + + for(size_t i = 0; i < retransmission.size(); ++i) { + const auto retransmitted_rn = plaintext_record_number(retransmission[i]); + + result.test_u64_eq("retransmission stays in epoch 0", retransmitted_rn.first, 0); + result.test_u64_eq("retransmission uses a fresh record sequence number", + retransmitted_rn.second, + original.size() + i); + + // the record payload (and hence the handshake message with + // its message_seq) is reused unchanged + result.test_bin_eq("retransmitted payload is identical", + std::span{retransmission[i].get()}.subspan(TLS::Size_Limits::DTLS_HEADER_SIZE), + std::span{original[i]}.subspan(TLS::Size_Limits::DTLS_HEADER_SIZE)); + } + + rl.clear_resend_buffer(); + result.test_is_true("nothing left to retransmit", + rl.prepare_unacknowledged_records(*policy, nullptr).empty()); + }), + + CHECK( + "retransmission of a mixed flight with protected records", + [&](Test::Result& result) { + const auto cs_server = make_cipher_state(TLS::Connection_Side::Server); + const auto cs_client = make_cipher_state(TLS::Connection_Side::Client); + + TLS::DTLS_Record_Layer rl_server{*policy}; + TLS::DTLS_Record_Layer rl_client{*policy}; + + // Simulate a server's first flight, i.e., use an unprotected + // record (ServerHello) followed by protected records (e.g. + // EncryptedExtensions, Finished). + Botan::secure_vector unprotected; + rl_server.prepare_handshake_record(packed(payload1), unprotected, *policy, nullptr); + Botan::secure_vector protected1; + Botan::secure_vector protected2; + rl_server.prepare_handshake_record(packed(payload2), protected1, *policy, cs_server.get()); + rl_server.prepare_handshake_record(packed(payload3), protected2, *policy, cs_server.get()); + + // The flight is lost and the server retransmits everything that + // was not acknowledged. + const auto retransmission = rl_server.prepare_unacknowledged_records(*policy, cs_server.get()); + result.require("three records retransmitted", retransmission.size() == 3); + + // The unprotected record is retransmitted in epoch 0 under a + // fresh record sequence number (RFC 9147 Section 5.2, see the + // test case above). + const auto rn = plaintext_record_number(retransmission[0]); + result.test_u64_eq("retransmission stays in epoch 0", rn.first, 0); + result.test_u64_eq("fresh record sequence number", rn.second, 1); + + // The protected records are freshly re-encrypted + const auto unified_header_len = TLS::UnifiedHeader_DTLS::expected_length(*policy, std::nullopt); + const auto ciphertext = [&](const auto& record) { return std::span{record}.subspan(unified_header_len); }; + result.test_bin_ne("fresh encryption of first protected record", + ciphertext(retransmission[1].get()), + ciphertext(protected1)); + result.test_bin_ne("fresh encryption of second protected record", + ciphertext(retransmission[2].get()), + ciphertext(protected2)); + + // The peer can read all retransmitted records. + const auto expected_payloads = std::array{payload1, payload2, payload3}; + const auto expected_epochs = std::array{TLS::EpochNumber::unprotected(), + TLS::EpochNumber::handshake_traffic(), + TLS::EpochNumber::handshake_traffic()}; + const auto expected_seqnos = std::array{1, 2, 3}; + for(size_t i = 0; i < retransmission.size(); ++i) { + result.require("ingestion is successful", rl_client.copy_data(retransmission[i].get(), true)); + + // Plaintext records from an earlier epoch are discarded once a + // cryptographic association exists (RFC 9147 Section 4.2.1), so + // the retransmitted ServerHello is read without one. + const auto read = (expected_epochs[i].is_protected()) ? rl_client.next_record(cs_client.get()) + : rl_client.next_record(); + result.require("record is delivered", !std::holds_alternative(read)); + const auto& content = std::get(read); + result.test_bin_eq("payload round-trips", content.payload, expected_payloads[i]); + result.test_is_true("epoch", content.epoch == expected_epochs[i]); + result.test_u64_eq("fresh record sequence number", content.sequence_number.value(), expected_seqnos[i]); + } + + rl_server.clear_resend_buffer(); + result.test_is_true("nothing left to retransmit", + rl_server.prepare_unacknowledged_records(*policy, nullptr).empty()); + }), + + CHECK("acknowledged records are not retransmitted", + [&](Test::Result& result) { + TLS::DTLS_Record_Layer rl_out{*policy}; + TLS::DTLS_Record_Layer rl_in{*policy}; + + Botan::secure_vector out; + const auto rn = rl_out.prepare_handshake_record(packed(payload1), out, *policy, nullptr); + result.test_is_true("record is unacknowledged", rl_out.has_unacknowledged_record(rn)); + + // The peer receives the record and queues an acknowledgement + // for it (RFC 9147 Section 7). + result.require("ingestion is successful", rl_in.copy_data(out, false)); + const auto read = rl_in.next_record(); + result.require("record is delivered", !std::holds_alternative(read)); + const auto& content = std::get(read); + + result.test_is_true("nothing to acknowledge yet", !rl_in.has_outstanding_acknowledgements()); + rl_in.acknowledge_handshake_record( + TLS::RecordNumber{content.epoch.value(), content.sequence_number.value()}, *policy); + result.test_is_true("acknowledgement is queued", rl_in.has_outstanding_acknowledgements()); + + // The sender consumes the ACK record and stops retransmitting. + result.test_enum_eq("all records acknowledged", + rl_out.handle_acknowledgements(rl_in.acknowledgements()), + TLS::ACK_Effect::ACKed_Everything); + result.test_is_true("no unacknowledged records", !rl_out.has_unacknowledged_records()); + result.test_is_true("nothing left to retransmit", + rl_out.prepare_unacknowledged_records(*policy, nullptr).empty()); + + rl_in.clear_outstanding_acknowledgements(); + result.test_is_true("acknowledgement queue is cleared", !rl_in.has_outstanding_acknowledgements()); + }), + + CHECK("acknowledgements for any transmission clear the retransmission state", + [&](Test::Result& result) { + TLS::DTLS_Record_Layer rl{*policy}; + + Botan::secure_vector out_a; + Botan::secure_vector out_b; + const auto rn_a1 = rl.prepare_handshake_record(packed(payload1), out_a, *policy, nullptr); + const auto rn_b1 = rl.prepare_handshake_record(packed(payload2), out_b, *policy, nullptr); + + const auto retransmission = rl.prepare_unacknowledged_records(*policy, nullptr); + result.require("two records retransmitted", retransmission.size() == 2); + + // Each retransmission gets a fresh record sequence number, but + // the record stays associated with all of its transmission + // numbers: acknowledging ANY of them clears it. + const TLS::RecordNumber rn_a2{TLS::EpochNumber::unprotected(), + plaintext_record_number(retransmission[0]).second}; + const TLS::RecordNumber rn_b2{TLS::EpochNumber::unprotected(), + plaintext_record_number(retransmission[1]).second}; + + result.test_is_true("original transmission of first record is pending", + rl.has_unacknowledged_record(rn_a1)); + result.test_is_true("retransmission of first record is pending", rl.has_unacknowledged_record(rn_a2)); + result.test_is_true("original transmission of second record is pending", + rl.has_unacknowledged_record(rn_b1)); + result.test_is_true("retransmission of second record is pending", rl.has_unacknowledged_record(rn_b2)); + + const TLS::RecordNumber bogus{TLS::EpochNumber::handshake_traffic(), 42}; + result.test_enum_eq("unknown acknowledgement is ignored", + rl.handle_acknowledgements(TLS::ACKs({bogus})), + TLS::ACK_Effect::ACKed_Nothing); + result.test_is_true("records are still pending", rl.has_unacknowledged_records()); + + // Acknowledge the original transmission of the first record + // and the retransmission of the second record. + result.test_enum_eq("all records acknowledged", + rl.handle_acknowledgements(TLS::ACKs({rn_a1, rn_b2})), + TLS::ACK_Effect::ACKed_Everything); + result.test_is_true("no unacknowledged records", !rl.has_unacknowledged_records()); + result.test_is_true("nothing left to retransmit", + rl.prepare_unacknowledged_records(*policy, nullptr).empty()); + }), + + CHECK("effects of an ACK on the resend buffer", + [&](Test::Result& result) { + TLS::DTLS_Record_Layer rl{*policy}; + + // With nothing outstanding, an ACK cannot acknowledge anything: + // the (previously and still empty) resend buffer stays empty. + const TLS::RecordNumber unknown{TLS::EpochNumber::handshake_traffic(), 42}; + result.test_enum_eq("empty resend buffer -> ACKed_Nothing", + rl.handle_acknowledgements(TLS::ACKs({unknown})), + TLS::ACK_Effect::ACKed_Nothing); + + // Even an ACK for a record number that was outstanding before + // the resend buffer was cleared (e.g. implicitly acknowledged by + // handshake progress) does not acknowledge anything. + Botan::secure_vector out; + const auto rn_cleared = rl.prepare_handshake_record(packed(payload1), out, *policy, nullptr); + rl.clear_resend_buffer(); + result.test_is_true("resend buffer is empty", !rl.has_unacknowledged_records()); + result.test_enum_eq("ACK for a cleared buffer -> ACKed_Nothing", + rl.handle_acknowledgements(TLS::ACKs({rn_cleared})), + TLS::ACK_Effect::ACKed_Nothing); + + // With two records outstanding, an ACK without record numbers + // and an ACK for unknown record numbers are both no-ops. + Botan::secure_vector out_a; + Botan::secure_vector out_b; + const auto rn_a = rl.prepare_handshake_record(packed(payload1), out_a, *policy, nullptr); + const auto rn_b = rl.prepare_handshake_record(packed(payload2), out_b, *policy, nullptr); + result.require("two records are outstanding", rl.has_unacknowledged_records()); + + result.test_enum_eq("empty ACK -> ACKed_Nothing", + rl.handle_acknowledgements(TLS::ACKs(std::vector{})), + TLS::ACK_Effect::ACKed_Nothing); + result.test_enum_eq("ACK for unknown record numbers -> ACKed_Nothing", + rl.handle_acknowledgements(TLS::ACKs({unknown})), + TLS::ACK_Effect::ACKed_Nothing); + result.test_is_true("both records are still outstanding", rl.has_unacknowledged_records()); + + // An ACK covering one of the outstanding records makes partial + // progress; the other one remains to be retransmitted. + result.test_enum_eq("partial ACK -> ACKed_Something", + rl.handle_acknowledgements(TLS::ACKs({rn_a})), + TLS::ACK_Effect::ACKed_Something); + result.test_is_true("one record is still outstanding", rl.has_unacknowledged_records()); + + // The ACK for the remaining record completes the flight. + result.test_enum_eq("complete ACK -> ACKed_Everything", + rl.handle_acknowledgements(TLS::ACKs({rn_b})), + TLS::ACK_Effect::ACKed_Everything); + result.test_is_true("no records are outstanding", !rl.has_unacknowledged_records()); + }), + + CHECK( + "acknowledgement queue is trimmed to the most recent record numbers", + [&](Test::Result& result) { + const auto ack_policy = create_policy({}, 2); + TLS::DTLS_Record_Layer rl{*policy}; + + rl.acknowledge_handshake_record({TLS::EpochNumber::handshake_traffic(), 0}, *ack_policy); + rl.acknowledge_handshake_record({TLS::EpochNumber::handshake_traffic(), 1}, *ack_policy); + rl.acknowledge_handshake_record({TLS::EpochNumber::handshake_traffic(), 2}, *ack_policy); + + // RFC 9147 7.1: If space is limited, implementations SHOULD + // favor including records which have not yet been acknowledged. + const auto acks = rl.acknowledgements(); + result.require("queue is trimmed to the policy limit", acks.record_numbers().size() == 2); + result.test_u64_eq("oldest acknowledgement was evicted", acks.record_numbers().front().sequence_number, 1); + result.test_u64_eq("newest acknowledgement is retained", acks.record_numbers().back().sequence_number, 2); + }), + }; +} + +std::vector unified_header() { + return { + CHECK("empty input is rejected", + [&](Test::Result& result) { + const auto bytes = std::array{}; + result.test_throws("empty input is rejected", [&] { parse_header(bytes, std::nullopt); }); + }), + + CHECK("input with malformed header byte is rejected", + [&](Test::Result& result) { + // epoch_bits=0, no CID, short seq_no, no length + // prefix is not 0b001xxxxx, so it is malformed + constexpr uint8_t malformed_header = 0b11100000; + const auto bytes = std::array{malformed_header, 0x00 /* seqno */}; + result.test_throws("malformed header is rejected", [&] { parse_header(bytes, std::nullopt); }); + }), + + CHECK("input without sequence number is rejected", + [&](Test::Result& result) { + // epoch_bits=2, no CID, short seq_no, no length + constexpr uint8_t minimal_header = 0b00100010; + const auto bytes = std::array{minimal_header}; + result.test_throws("missing seqno is rejected", [&] { parse_header(bytes, std::nullopt); }); + }), + + CHECK("input with too short sequence number is rejected", + [&](Test::Result& result) { + // epoch_bits=2, no CID, long seq_no, no length + constexpr uint8_t minimal_header_long_seqno = 0b00101010; + const auto bytes = std::array{minimal_header_long_seqno, 0x00}; + result.test_throws("too short seqno is rejected", [&] { parse_header(bytes, std::nullopt); }); + }), + + CHECK("minimal unified header", + [&](Test::Result& result) { + // epoch_bits=2, no CID, short seq_no, no length + constexpr uint8_t minimal_header = 0b00100010; + const auto bytes = std::array{minimal_header, 0b00101010}; + + const auto header = parse_header(bytes, std::nullopt); + result.test_u8_eq("epoch bits", header.epoch_bits, 2); + result.test_opt_is_null("no CID", header.connection_id); + result.test_is_true("short seq no", std::holds_alternative(header.sequence_number)); + result.test_u8_eq("seq_no", std::get(header.sequence_number), 42); + result.test_opt_is_null("no payload length", header.length); + result.test_sz_eq("header length", header.serialized_byte_length(), 2); + }), + + CHECK("input with missing payload length is rejected", + [&](Test::Result& result) { + // epoch_bits=2, no CID, short seq_no, with length + constexpr uint8_t minimal_header_with_length = 0b00100110; + + const auto bytes = std::array{minimal_header_with_length, 0x00 /* seqno */}; + result.test_throws("missing payload length is rejected", [&] { parse_header(bytes, std::nullopt); }); + }), + + CHECK("input with truncated payload length is rejected", + [&](Test::Result& result) { + // epoch_bits=2, no CID, short seq_no, with length + constexpr uint8_t minimal_header_with_length = 0b00100110; + + const auto bytes = std::array{ + minimal_header_with_length, + 0x00 /* seqno */, + 0x01 /* partial payload length */, + }; + result.test_throws("partial payload length is rejected", [&] { parse_header(bytes, std::nullopt); }); + }), + + CHECK("unified header with payload length", + [&](Test::Result& result) { + // epoch_bits=2, no CID, short seq_no, with length + constexpr uint8_t minimal_header_with_length = 0b00100110; + + // Parsing validates that the advertised payload is actually + // present in the input buffer. + const auto bytes = Botan::concat>( + std::array{ + minimal_header_with_length, + 0x00 /* seqno */, + 0x00, + 0x10 /* payload length */, + }, + std::vector(16, 0xAA) /* dummy payload */); + + const auto header = parse_header(bytes, std::nullopt); + result.test_u8_eq("epoch bits", header.epoch_bits, 2); + result.test_opt_is_null("no CID", header.connection_id); + result.test_is_true("short seq no", std::holds_alternative(header.sequence_number)); + result.test_u8_eq("seq_no", std::get(header.sequence_number), 0); + result.test_opt_not_null("has payload length", header.length); + result.test_u16_eq("payload length", *header.length, 16); + result.test_sz_eq("header length", header.serialized_byte_length(), 4); + }), + + CHECK("input with advertised but missing connection ID is rejected", + [&](Test::Result& result) { + const size_t connection_id_length = 7; + + // epoch_bits=2, with CID, short seq_no, no length + constexpr uint8_t minimal_header_with_cid = 0b00110010; + + const auto bytes = std::array{minimal_header_with_cid, 0x00 /* seqno */}; + result.test_throws("missing connection ID is rejected", + [&] { parse_header(bytes, connection_id_length); }); + }), + + CHECK("input with omitted connection ID is rejected", + [&](Test::Result& result) { + const size_t connection_id_length = 7; + + // epoch_bits=2, no CID, short seq_no, no length + constexpr uint8_t minimal_header_without_cid = 0b00100010; + + const auto bytes = std::array{ + minimal_header_without_cid, 0x00 /* seqno */ + }; + + result.test_throws("omitted connection ID is rejected", + [&] { parse_header(bytes, connection_id_length); }); + }), + + CHECK("input with truncated connection ID is rejected", + [&](Test::Result& result) { + const size_t connection_id_length = 7; + + // epoch_bits=2, with CID, short seq_no, no length + constexpr uint8_t minimal_header_with_cid = 0b00110010; + + // clang-format off + const auto bytes = std::array{ + minimal_header_with_cid, + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // partial connection ID + 0x00 // sequence number + }; + // clang-format on + + result.test_throws("partial connection ID is rejected", + [&] { parse_header(bytes, connection_id_length); }); + }), + + CHECK("full unified header", + [&](Test::Result& result) { + const size_t connection_id_length = 7; + + // epoch_bits=2, with CID, long seq_no, with length + constexpr uint8_t full_header = 0b00111110; + + // Parsing validates that the advertised payload is actually + // present in the input buffer. + // clang-format off + const auto bytes = Botan::concat>( + std::array{ + full_header, // header + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // connection ID + 0x00, 0x2A, // sequence number + 0x00, 0x10 // payload length + }, + std::vector(16, 0xAA) /* dummy payload */); + // clang-format on + + const auto header = parse_header(bytes, connection_id_length); + result.test_u8_eq("epoch bits", header.epoch_bits, 2); + result.test_opt_not_null("has CID", header.connection_id); + result.test_bin_eq("CID matches", *header.connection_id, "01020304050607"); + result.test_is_true("long seq no", std::holds_alternative(header.sequence_number)); + result.test_u16_eq("seq_no", std::get(header.sequence_number), 42); + result.test_opt_not_null("has payload length", header.length); + result.test_u16_eq("payload length", *header.length, 16); + result.test_sz_eq("header length", header.serialized_byte_length(), 12); + }), + + CHECK("unified header with unsolicited CID is rejected", + [&](Test::Result& result) { + // clang-format off + const auto bytes = std::array{ + 0b00111101, // header + 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // connection ID + 0x00, 0x2A, // sequence number + 0x00, 0x10 // payload length + }; + // clang-format on + + result.test_throws("unsolicited CID is rejected", [&] { parse_header(bytes, std::nullopt); }); + }), + + CHECK("rendering a minimal unified header", + [&](Test::Result& result) { + const auto header = TLS::UnifiedHeader_DTLS{ + .epoch_bits = 1, + .connection_id = std::nullopt, + .sequence_number = uint8_t{42}, + .length = std::nullopt, + }; + + result.test_sz_eq("header length", header.serialized_byte_length(), 2); + + const auto bytes = header.serialize(); + result.test_bin_eq("serialization", bytes, "21 2A"); + }), + + CHECK("rendering a full unified header", + [&](Test::Result& result) { + const auto header = TLS::UnifiedHeader_DTLS{ + .epoch_bits = 2, + .connection_id = Botan::TLS::ConnectionID({0x01, 0x02, 0x03, 0x04}), + .sequence_number = uint16_t{42}, + .length = uint16_t{17}, + }; + + result.test_sz_eq("header length", header.serialized_byte_length(), 9); + + const auto bytes = header.serialize(); + result.test_bin_eq("serialization", bytes, "3E 01 02 03 04 00 2A 00 11"); + }), + + CHECK("rendering a unified header without a CID", + [&](Test::Result& result) { + const auto header = TLS::UnifiedHeader_DTLS{ + .epoch_bits = 3, + .connection_id = std::nullopt, + .sequence_number = uint16_t{42}, + .length = uint16_t{17}, + }; + + result.test_sz_eq("header length", header.serialized_byte_length(), 5); + + const auto bytes = header.serialize(); + result.test_bin_eq("serialization", bytes, "2F 00 2A 00 11"); + }), + + CHECK("rendering a unified header without payload length", + [&](Test::Result& result) { + const auto header = TLS::UnifiedHeader_DTLS{ + .epoch_bits = 0, + .connection_id = Botan::TLS::ConnectionID({0x01, 0x02, 0x03, 0x04}), + .sequence_number = uint8_t{42}, + .length = std::nullopt, + }; + + result.test_sz_eq("header length", header.serialized_byte_length(), 6); + + const auto bytes = header.serialize(); + result.test_bin_eq("serialization", bytes, "30 01 02 03 04 2A"); + }), + + CHECK("rendering into a too-short buffer is rejected", + [&](Test::Result& result) { + const auto header = TLS::UnifiedHeader_DTLS{ + .epoch_bits = 0, + .connection_id = Botan::TLS::ConnectionID({0x01, 0x02, 0x03, 0x04}), + .sequence_number = uint8_t{42}, + .length = std::nullopt, + }; + + std::array too_short{}; + result.test_sz_lt("buffer is too short", too_short.size(), header.serialized_byte_length()); + result.test_throws("rendering into too-short buffer is rejected", + [&] { header.serialize_to(too_short); }); + }), + + CHECK("UnifiedHeader pre-determine header length", + [&](Test::Result& result) { + const auto policy = create_policy(); + + const size_t r1 = TLS::UnifiedHeader_DTLS::expected_length(*policy, std::nullopt); + result.test_sz_eq("UnifiedHeader w/o CID (default seqno and length)", r1, 5); + + const size_t r2 = TLS::UnifiedHeader_DTLS::expected_length(*policy, 0); + result.test_sz_eq("UnifiedHeader w/ empty CID (default seqno and length)", r2, 5); + + const size_t r3 = TLS::UnifiedHeader_DTLS::expected_length(*policy, 4); + result.test_sz_eq("UnifiedHeader w/ 4 byte CID (default seqno and length)", r3, 9); + }), + }; +} + +std::vector replay_window() { + return { + CHECK("new window accepts sequence number 0", + [](Test::Result& result) { + TLS::Replay_Window_13 window; + result.test_is_true("accepts seqno 0", window.accept(0)); + }), + + CHECK("new window accepts sequence number > 0", + [](Test::Result& result) { + TLS::Replay_Window_13 window; + result.test_is_true("accepts seqno 1", window.accept(1)); + }), + + CHECK("window rejects duplicate sequence number", + [](Test::Result& result) { + TLS::Replay_Window_13 window; + result.test_is_true("accepts seqno 0", window.accept(0)); + result.test_is_false("rejects duplicate seqno 0", window.accept(0)); + }), + + CHECK("window rejects sequence numbers that are too old", + [](Test::Result& result) { + TLS::Replay_Window_13 window; + window.accept(TLS::Replay_Window_13::window_size); + result.test_is_false("rejects too-old seqno", window.accept(0)); + }), + + CHECK("window slides along when higher sequence numbers are received", + [](Test::Result& result) { + TLS::Replay_Window_13 window; + result.test_is_true("receive 0", window.accept(0)); + result.test_is_true("receive 5", window.accept(5)); + + // Shift the window far enough to let 0, 1, and 2 fall off the + // left side of the window. + result.test_is_true("receive higher value", window.accept(TLS::Replay_Window_13::window_size + 2)); + result.test_is_false("rejects duplicate 5", window.accept(5)); + + result.test_is_false("rejects too-old duplicate 0", window.accept(0)); + result.test_is_false("rejects too-old 1", window.accept(1)); + result.test_is_false("rejects too-old 2", window.accept(2)); + result.test_is_true("receive still-acceptable 3", window.accept(3)); + }), + + CHECK("window slides along for a large jump in sequence numbers", + [](Test::Result& result) { + constexpr auto large_seqno = TLS::Replay_Window_13::window_size * 5; + + TLS::Replay_Window_13 window; + result.test_is_true("receive 0", window.accept(0)); + result.test_is_true("receive a much-later seqno", window.accept(large_seqno)); + + result.test_is_false("rejects duplicate of much-later seqno", window.accept(large_seqno)); + result.test_is_false("rejects too-old seqno", + window.accept(large_seqno - TLS::Replay_Window_13::window_size)); + result.test_is_true("receive still-acceptable seqno", window.accept(large_seqno - 1)); + }), + + CHECK("window works close to the maximum sequence number", + [](Test::Result& result) { + TLS::Replay_Window_13 window; + constexpr auto max_seqno = std::numeric_limits::max(); + + result.test_is_true("receive max_seqno - 1", window.accept(max_seqno - 1)); + result.test_is_true("receive max_seqno", window.accept(max_seqno)); + + result.test_is_false("rejects duplicate max_seqno - 1", window.accept(max_seqno - 1)); + result.test_is_false("rejects duplicate max_seqno", window.accept(max_seqno)); + result.test_is_false("rejects too-old max_seqno - window_size", + window.accept(max_seqno - TLS::Replay_Window_13::window_size)); + }), + + CHECK("window tracks a completely filled window", + [](Test::Result& result) { + TLS::Replay_Window_13 window; + + for(uint64_t i = 0; i < TLS::Replay_Window_13::window_size; ++i) { + result.test_is_true("receive " + std::to_string(i), window.accept(i)); + } + + for(uint64_t i = 0; i < TLS::Replay_Window_13::window_size; ++i) { + result.test_is_false("rejects replay of " + std::to_string(i), window.accept(i)); + } + + // Slide by one: 0 falls off the left edge, everything else + // is still tracked as a duplicate. + result.test_is_true("receive window_size", window.accept(TLS::Replay_Window_13::window_size)); + result.test_is_false("rejects too-old 0", window.accept(0)); + + for(uint64_t i = 1; i <= TLS::Replay_Window_13::window_size; ++i) { + result.test_is_false("rejects replay of " + std::to_string(i) + " after slide", window.accept(i)); + } + }), + }; +} + +std::vector sequence_number_reconstruction() { + // Shorthands for the 8-bit and 16-bit sequence number hints that may + // appear in the DTLS 1.3 unified header (RFC 9147 Section 4 Figure 3). + const auto hint8 = [](uint64_t hint) { return TLS::SequenceNumberHint{static_cast(hint)}; }; + const auto hint16 = [](uint64_t hint) { return TLS::SequenceNumberHint{static_cast(hint)}; }; + + return { + CHECK("in-order records reconstruct to the next sequence number", + [&](Test::Result& result) { + result.test_u64_eq("8-bit hint", TLS::reconstruct_full_sequence_number(5, hint8(6)), 6); + result.test_u64_eq("16-bit hint", TLS::reconstruct_full_sequence_number(5, hint16(6)), 6); + }), + + CHECK("the first record in an epoch may have sequence number 0", + [&](Test::Result& result) { + result.test_u64_eq("8-bit hint", TLS::reconstruct_full_sequence_number(0, hint8(0)), 0); + result.test_u64_eq("16-bit hint", TLS::reconstruct_full_sequence_number(0, hint16(0)), 0); + }), + + CHECK("reordered records reconstruct to sequence numbers in the past", + [&](Test::Result& result) { + // Record 266 arrives after 300 was already deprotected + result.test_u64_eq( + "8-bit hint within window", TLS::reconstruct_full_sequence_number(300, hint8(10)), 266); + + // Record 255 arrives after 256 was already deprotected + result.test_u64_eq( + "8-bit hint across window boundary", TLS::reconstruct_full_sequence_number(256, hint8(255)), 255); + result.test_u64_eq("8-bit hint across window boundary (later)", + TLS::reconstruct_full_sequence_number(512, hint8(255)), + 511); + + // Record 65535 arrives after 65536 was already deprotected + result.test_u64_eq("16-bit hint across window boundary", + TLS::reconstruct_full_sequence_number(65536, hint16(65535)), + 65535); + }), + + CHECK("records after packet loss reconstruct to sequence numbers in the future", + [&](Test::Result& result) { + result.test_u64_eq("8-bit hint", TLS::reconstruct_full_sequence_number(0, hint8(42)), 42); + result.test_u64_eq("16-bit hint", TLS::reconstruct_full_sequence_number(0, hint16(1000)), 1000); + result.test_u64_eq( + "8-bit hint across window boundary", TLS::reconstruct_full_sequence_number(255, hint8(0)), 256); + result.test_u64_eq( + "16-bit hint across window boundary", TLS::reconstruct_full_sequence_number(65535, hint16(0)), 65536); + }), + + CHECK("at epoch start any hint reconstructs to itself", + [&](Test::Result& result) { + // Nothing was deprotected in the epoch, yet, so the closest + // valid (i.e. non-negative) full sequence number is the hint. + for(uint64_t hint : {0, 1, 127, 128, 129, 200, 255}) { + result.test_u64_eq( + "8-bit hint " + std::to_string(hint), TLS::reconstruct_full_sequence_number(0, hint8(hint)), hint); + } + + for(uint64_t hint : {0, 1, 32767, 32768, 32769, 40000, 65535}) { + result.test_u64_eq("16-bit hint " + std::to_string(hint), + TLS::reconstruct_full_sequence_number(0, hint16(hint)), + hint); + } + }), + + CHECK( + "hints in the upper half-window at epoch start do not underflow", + [&](Test::Result& result) { + // Regression test: subtracting the window from a candidate + // smaller than the window would underflow below zero. The + // closest valid sequence number is the hint itself. + result.test_u64_eq("8-bit hint, nothing seen", TLS::reconstruct_full_sequence_number(0, hint8(200)), 200); + result.test_u64_eq("8-bit hint, little seen", TLS::reconstruct_full_sequence_number(100, hint8(255)), 255); + result.test_u64_eq( + "16-bit hint, nothing seen", TLS::reconstruct_full_sequence_number(0, hint16(40000)), 40000); + result.test_u64_eq( + "16-bit hint, little seen", TLS::reconstruct_full_sequence_number(1000, hint16(65535)), 65535); + }), + + CHECK( + "hints at exactly half-window distance resolve to the higher sequence number", + [&](Test::Result& result) { + // 272 and 528 are both 128 away from the expected 301 + 99 = 400 + result.test_u64_eq("8-bit tie below expected", TLS::reconstruct_full_sequence_number(399, hint8(16)), 528); + + // 173 and 429 are both 128 away from the expected 301 + result.test_u64_eq("8-bit tie above expected", TLS::reconstruct_full_sequence_number(300, hint8(173)), 429); + + // 7233 and 72769 are both 32768 away from the expected 40001 + result.test_u64_eq( + "16-bit tie below expected", TLS::reconstruct_full_sequence_number(40000, hint16(7233)), 72769); + + // 37233 and 102769 are both 32768 away from the expected 70001 + result.test_u64_eq( + "16-bit tie above expected", TLS::reconstruct_full_sequence_number(70000, hint16(37233)), 102769); + }), + + CHECK("records up to half a window ahead reconstruct to the future", + [&](Test::Result& result) { + result.test_u64_eq("8-bit hint, 127 ahead", TLS::reconstruct_full_sequence_number(0, hint8(128)), 128); + result.test_u64_eq( + "16-bit hint, 32767 ahead", TLS::reconstruct_full_sequence_number(0, hint16(32768)), 32768); + }), + + CHECK("reconstruction preserves the high bits of large sequence numbers", + [&](Test::Result& result) { + constexpr uint64_t base32 = uint64_t{1} << 32; + result.test_u64_eq("8-bit hint, next across boundary", + TLS::reconstruct_full_sequence_number(base32 + 255, hint8(0)), + base32 + 256); + result.test_u64_eq("8-bit hint, reordered across boundary", + TLS::reconstruct_full_sequence_number(base32 + 256, hint8(255)), + base32 + 255); + + constexpr uint64_t base48 = uint64_t{1} << 48; + result.test_u64_eq("16-bit hint, next across boundary", + TLS::reconstruct_full_sequence_number(base48 + 65535, hint16(0)), + base48 + 65536); + result.test_u64_eq("16-bit hint, reordered across boundary", + TLS::reconstruct_full_sequence_number(base48 + 65536, hint16(65535)), + base48 + 65535); + }), + + CHECK("the hint's bit width determines the reconstruction window", + [&](Test::Result& result) { + // The same hint value reconstructs differently depending on + // whether 8 or 16 bits were transmitted on the wire. + result.test_u64_eq("8-bit hint", TLS::reconstruct_full_sequence_number(300, hint8(44)), 300); + result.test_u64_eq("16-bit hint", TLS::reconstruct_full_sequence_number(300, hint16(44)), 44); + }), + }; +} + +} // namespace + +BOTAN_REGISTER_TEST_FN("tls", "dtls_record_layer_13_clienthello", read_clienthello_record); +BOTAN_REGISTER_TEST_FN("tls", "dtls_record_layer_13_protected", protected_records); +BOTAN_REGISTER_TEST_FN("tls", "dtls_record_layer_13_retransmission", retransmission); +BOTAN_REGISTER_TEST_FN("tls", "dtls_record_layer_13_unified_header", unified_header); +BOTAN_REGISTER_TEST_FN("tls", "dtls_record_layer_13_replay_window", replay_window); +BOTAN_REGISTER_TEST_FN("tls", "dtls_record_layer_13_sequence_number_reconstruction", sequence_number_reconstruction); + +} // namespace Botan_Tests + +#endif diff --git a/src/tests/test_tls_dtls_timer.cpp b/src/tests/test_tls_dtls_timer.cpp new file mode 100644 index 00000000000..14bdb1d0955 --- /dev/null +++ b/src/tests/test_tls_dtls_timer.cpp @@ -0,0 +1,1025 @@ +/* +* (C) 2026 Jack Lloyd +* (C) 2026 Amos Treiber, René Meusel - Rohde & Schwarz Networks and Cybersecurity GmbH +* +* Botan is released under the Simplified BSD License (see license.txt) +*/ + +#include "tests.h" + +#if defined(BOTAN_HAS_DTLS_13) + + #include + #include + #include + +namespace Botan_Tests { + +namespace { + +class Timer_Callbacks final : public Botan::TLS::Callbacks { + public: + void tls_emit_data(std::span /*data*/) override {} + + void tls_record_received(uint64_t /*seq*/, std::span /*data*/) override {} + + void tls_alert(Botan::TLS::Alert /*alert*/) override {} + + uint64_t tls_current_monotonic_clock_ms() override { return m_now_ms; } + + void tls_register_deferred_operation(uint64_t monotonic_delay_ms, std::function op) override { + const uint64_t deadline_ms = tls_current_monotonic_clock_ms() + monotonic_delay_ms; + m_deferred_ops.emplace_back(Deferred_Operation{ + .deadline_ms = deadline_ms, + .op = std::move(op), + }); + } + + void set_clock_forward(std::chrono::milliseconds delta) { m_now_ms += delta.count(); } + + void advance(std::chrono::milliseconds delta) { + m_now_ms += delta.count(); + + // Collect the due operations before invoking them, because an invoked + // operation may register new deferred operations (e.g. the retransmission + // timer re-arms itself) and thereby invalidate iterators of m_deferred_ops. + std::vector> due_ops; + std::erase_if(m_deferred_ops, [this, &due_ops](Deferred_Operation& op) { + if(op.deadline_ms <= m_now_ms) { + due_ops.emplace_back(std::move(op.op)); + return true; + } + return false; + }); + + for(const auto& op : due_ops) { + op(); + } + } + + [[nodiscard]] std::function get_next_scheduled_operation() const { + const auto next_op = std::min_element( + m_deferred_ops.begin(), m_deferred_ops.end(), [](const Deferred_Operation& a, const Deferred_Operation& b) { + return a.deadline_ms < b.deadline_ms; + }); + + if(next_op == m_deferred_ops.end()) { + throw Botan_Tests::Test_Error("No scheduled operations"); + } + + return next_op->op; + } + + [[nodiscard]] size_t deferred_op_count() const { return m_deferred_ops.size(); } + + [[nodiscard]] uint64_t next_remaining_ms() const { + const auto next_op = std::min_element( + m_deferred_ops.begin(), m_deferred_ops.end(), [](const Deferred_Operation& a, const Deferred_Operation& b) { + return a.deadline_ms < b.deadline_ms; + }); + + if(next_op == m_deferred_ops.end()) { + throw Botan_Tests::Test_Error("No scheduled operations"); + } + + return next_op->deadline_ms > m_now_ms ? next_op->deadline_ms - m_now_ms : 0; + } + + private: + struct Deferred_Operation { + uint64_t deadline_ms; + std::function op; + }; + + uint64_t m_now_ms = 0; + std::vector m_deferred_ops; +}; + +class Timer_Operation final { + public: + Timer_Operation() = default; + Timer_Operation(const Timer_Operation&) = delete; + Timer_Operation& operator=(const Timer_Operation&) = delete; + Timer_Operation(Timer_Operation&&) = default; + Timer_Operation& operator=(Timer_Operation&&) = default; + ~Timer_Operation() = default; + + std::function callback() { + return [this]() { ++m_runs; }; + } + + // NOLINTNEXTLINE(*-explicit-conversions) + operator bool() const { return m_runs > 0; } + + // NOLINTNEXTLINE(*-explicit-conversions) + operator uint32_t() const { return m_runs; } + + private: + uint32_t m_runs = 0; +}; + +class Retransmission_Test_Policy final : public Botan::TLS::Policy { + public: + Retransmission_Test_Policy(std::chrono::milliseconds initial_timeout, + std::chrono::milliseconds maximum_timeout, + std::optional flight_timeout, + std::optional maximum_retransmissions) : + m_initial_timeout(initial_timeout), + m_maximum_timeout(maximum_timeout), + m_flight_timeout(flight_timeout), + m_maximum_retransmissions(maximum_retransmissions) {} + + size_t dtls_initial_timeout() const override { return static_cast(m_initial_timeout.count()); } + + size_t dtls_maximum_timeout() const override { return static_cast(m_maximum_timeout.count()); } + + std::optional dtls_flight_timeout() const override { + // TODO(C++23): std::optional::transform + if(m_flight_timeout.has_value()) { + return static_cast(m_flight_timeout->count()); + } + return std::nullopt; + } + + std::optional dtls_maximum_retransmissions() const override { return m_maximum_retransmissions; } + + private: + std::chrono::milliseconds m_initial_timeout; + std::chrono::milliseconds m_maximum_timeout; + std::optional m_flight_timeout; + std::optional m_maximum_retransmissions; +}; + +using namespace Botan; +using namespace Botan::TLS; +using namespace std::chrono_literals; + +std::vector singleshot_timer() { + return { + CHECK("deferred operation runs after deadline", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + auto token = SingleshotTimer::start(cb, 100ms, op.callback()); + + result.test_is_true("token is valid", token); + result.test_is_true("token is armed", token.armed()); + result.test_u64_eq("remaining time is the full delay", token.remaining(*cb).value_or(-1ms).count(), 100); + + result.test_is_false("did not run yet", op); + + cb->set_clock_forward(10ms); + const auto early_op = cb->get_next_scheduled_operation(); + early_op(); + result.test_is_false("early invocation did not run operation", op); + result.test_is_true("timer still armed after early invocation", token.armed()); + result.test_u64_eq("re-armed for remaining time", cb->next_remaining_ms(), 90); + result.test_u64_eq( + "accessor also reports the re-armed remaining time", token.remaining(*cb).value_or(-1ms).count(), 90); + const auto op_count_after_early = cb->deferred_op_count(); + early_op(); + result.test_sz_eq( + "duplicate early invocation did not schedule again", cb->deferred_op_count(), op_count_after_early); + + cb->advance(89ms); + result.test_is_false("still didn't run yet", op); + result.test_u64_eq("one millisecond of remaining time", token.remaining(*cb).value_or(-1ms).count(), 1); + cb->advance(1ms); + result.test_is_true("deferred operation ran", op); + + result.test_is_false("token is no longer valid", token); + result.test_is_false("token is no longer armed", token.armed()); + result.test_is_false("no remaining time after the operation ran", token.remaining(*cb).has_value()); + }), + + CHECK("detached operation runs after deadline", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + SingleshotTimer::start_detached(cb, 100ms, op.callback()); + + result.test_is_false("did not run yet", op); + + cb->set_clock_forward(10ms); + const auto early_op = cb->get_next_scheduled_operation(); + early_op(); + result.test_is_false("early invocation did not run operation", op); + result.test_u64_eq("re-armed for remaining time", cb->next_remaining_ms(), 90); + const auto op_count_after_early = cb->deferred_op_count(); + early_op(); + result.test_sz_eq( + "duplicate early invocation did not schedule again", cb->deferred_op_count(), op_count_after_early); + + cb->advance(89ms); + result.test_is_false("still didn't run yet", op); + cb->advance(1ms); + result.test_is_true("deferred operation ran", op); + }), + + CHECK("deferred operation runs only once, even when called multiple times", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + auto token = SingleshotTimer::start(cb, 100ms, op.callback()); + + result.test_is_false("did not run yet", op); + + cb->set_clock_forward(100ms); + const auto scheduled_op = cb->get_next_scheduled_operation(); + result.test_is_true("remaining time is available at the deadline", token.remaining(*cb).has_value()); + result.test_u64_eq( + "remaining time clamps to zero at the deadline", token.remaining(*cb).value_or(-1ms).count(), 0); + scheduled_op(); + result.test_is_true("deferred operation ran", op); + scheduled_op(); + result.test_u32_eq("deferred operation ran only once", op, 1); + result.test_is_false("no remaining time after the operation ran", token.remaining(*cb).has_value()); + + cb->advance(100ms); + result.test_u32_eq("deferred operation didn't run after deadline", op, 1); + }), + + CHECK("detached operation runs only once, even when called multiple times", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + SingleshotTimer::start_detached(cb, 100ms, op.callback()); + + result.test_is_false("did not run yet", op); + + cb->set_clock_forward(100ms); + const auto scheduled_op = cb->get_next_scheduled_operation(); + scheduled_op(); + result.test_is_true("deferred operation ran", op); + scheduled_op(); + result.test_u32_eq("deferred operation ran only once", op, 1); + + cb->advance(100ms); + result.test_u32_eq("deferred operation didn't run after deadline", op, 1); + }), + + CHECK("deferred operation does not re-run after throwing an exception", + [&](Test::Result& result) { + auto cb = std::make_shared(); + uint32_t runs = 0; + + auto token = SingleshotTimer::start(cb, 100ms, [&runs] { + ++runs; + throw TLS_Exception(Alert::None, "operation failed"); + }); + + result.test_is_true("token is armed", token.armed()); + + cb->set_clock_forward(100ms); + const auto scheduled_op = cb->get_next_scheduled_operation(); + result.test_throws( + "operation threw an exception", "operation failed", [&] { scheduled_op(); }); + + result.test_is_false("token is no longer armed", token.armed()); + result.test_is_false("no remaining time after the operation threw", token.remaining(*cb).has_value()); + + scheduled_op(); + result.test_u32_eq("operation did not re-run when called again", runs, 1); + + cb->advance(100ms); + result.test_u32_eq("operation did not re-run after the deadline", runs, 1); + }), + + CHECK("detached operation does not re-run after throwing an exception", + [&](Test::Result& result) { + auto cb = std::make_shared(); + uint32_t runs = 0; + + SingleshotTimer::start_detached(cb, 100ms, [&runs] { + ++runs; + throw TLS_Exception(Alert::None, "operation failed"); + }); + + cb->set_clock_forward(100ms); + const auto scheduled_op = cb->get_next_scheduled_operation(); + result.test_throws( + "operation threw an exception", "operation failed", [&] { scheduled_op(); }); + + scheduled_op(); + result.test_u32_eq("operation did not re-run when called again", runs, 1); + + cb->advance(100ms); + result.test_u32_eq("operation did not re-run after the deadline", runs, 1); + }), + + CHECK("early invocation honours the fudge", + [&](Test::Result& result) { + constexpr auto delay = 100ms; + const std::chrono::milliseconds fudge{DTLS_RETRANSMISSION_TIMER_FUDGE}; + + // Invoking the deferred operation with more than the fudge time + // remaining re-arms the timer for the rest of the original delay. + { + auto cb = std::make_shared(); + Timer_Operation op; + auto token = SingleshotTimer::start(cb, delay, op.callback()); + + const auto above_fudge = delay - fudge - 1ms; + cb->set_clock_forward(above_fudge); + cb->get_next_scheduled_operation()(); + result.test_is_false("invocation above the fudge did not run yet", op); + result.test_u64_eq( + "re-armed for the remaining time above the fudge", cb->next_remaining_ms(), fudge.count() + 1); + result.test_u64_eq("accessor also reports the remaining time above the fudge", + token.remaining(*cb).value_or(-1ms).count(), + fudge.count() + 1); + + cb->advance(above_fudge); + result.test_is_true("re-armed timer fires at the original deadline", op); + result.test_is_false("timer is no longer armed", token.armed()); + } + + // Invoking the deferred operation within the fudge time runs it + // immediately, as if the deadline had been reached. + { + auto cb = std::make_shared(); + Timer_Operation op; + auto token = SingleshotTimer::start(cb, delay, op.callback()); + + cb->set_clock_forward(delay - fudge); + cb->get_next_scheduled_operation()(); + result.test_is_true("invocation within the fudge runs immediately", op); + result.test_is_false("timer is no longer armed", token.armed()); + result.test_is_false("no remaining time after the fudged invocation", + token.remaining(*cb).has_value()); + } + }), + + CHECK("deferred operation can be cancelled", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + auto token = SingleshotTimer::start(cb, 100ms, op.callback()); + + result.test_is_true("token is valid", token); + result.test_is_true("token is armed", token.armed()); + + cb->set_clock_forward(10ms); + cb->get_next_scheduled_operation()(); + result.test_u64_eq( + "remaining time after the premature invocation", token.remaining(*cb).value_or(-1ms).count(), 90); + + token.cancel(); + result.test_is_false("token is no longer valid", token); + result.test_is_false("token is no longer armed", token.armed()); + result.test_is_false("no remaining time after cancellation", token.remaining(*cb).has_value()); + + cb->advance(100ms); + result.test_is_false("deferred operation did not run", op); + }), + + CHECK("deferred operation is cancelled when token is destroyed", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + { + auto token = SingleshotTimer::start(cb, 100ms, op.callback()); + + result.test_is_true("token is valid", token); + result.test_is_true("token is armed", token.armed()); + + cb->set_clock_forward(10ms); + cb->get_next_scheduled_operation()(); + } + + cb->advance(100ms); + result.test_is_false("deferred operation did not run", op); + }), + }; +} + +std::vector retransmission_timer() { + return { + CHECK("retransmission timer is not armed on construction", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 500ms, 3), cb); + + result.test_is_false("retransmission timer is not armed", timer.retransmissions_armed()); + result.test_is_false("flight timer is not armed", timer.flight_timeout_armed()); + result.test_is_false("no next timeout on construction", timer.next_timeout().has_value()); + + cb->advance(1000ms); + result.test_is_false("deferred operation did not run", op); + }), + + CHECK("cancelling a retransmission timer that does not run has no effect", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, {}, 3), cb); + + result.test_is_false("timer is not armed", timer.retransmissions_armed()); + + timer.cancel(); + result.test_is_false("timer is still not armed", timer.retransmissions_armed()); + + cb->advance(1000ms); + result.test_is_false("deferred operation did not run", op); + }), + + CHECK( + "starting a retransmission timer emits the deferred operation after the first timeout", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 500ms, 3), cb); + + timer.start(op.callback()); + result.test_is_true("retransmission timer is armed", timer.retransmissions_armed()); + result.test_is_true("flight timer is armed", timer.flight_timeout_armed()); + result.test_u64_eq( + "next timeout is the initial retransmission timeout", timer.next_timeout().value_or(-1ms).count(), 100); + + result.test_is_false("did not run yet", op); + cb->advance(99ms); + result.test_is_false("still didn't run yet", op); + cb->advance(1ms); + result.test_u32_eq("deferred operation ran once", op, 1); + + result.test_is_true("retransmission timer re-armed for retransmission", timer.retransmissions_armed()); + result.test_is_true("flight timer was not reset by the retransmission", timer.flight_timeout_armed()); + result.test_u64_eq( + "next timeout is the doubled retransmission timeout", timer.next_timeout().value_or(-1ms).count(), 200); + }), + + CHECK("retransmission timer re-emits with exponential backoff up to the maximum timeout", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, {}, {}), cb); + + timer.start(op.callback()); + result.test_is_true("timer is armed", timer.retransmissions_armed()); + result.test_is_false("flight timer is not armed", timer.flight_timeout_armed()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + + cb->set_clock_forward(50ms); + const auto early_retransmit = cb->get_next_scheduled_operation(); + result.test_no_throw("early retransmission timer invocation", [&] { early_retransmit(); }); + result.test_u32_eq("early invocation did not retransmit", op, 1); + result.test_is_true("timer still armed after early invocation", timer.retransmissions_armed()); + result.test_u64_eq( + "next timeout still targets the original deadline", timer.next_timeout().value_or(-1ms).count(), 150); + + // timeout doubled: 100ms -> 200ms + cb->advance(149ms); + result.test_u32_eq("did not retransmit before the doubled timeout", op, 1); + cb->advance(1ms); + result.test_u32_eq("second retransmission ran", op, 2); + + // timeout doubled again but capped: 400ms -> 250ms + cb->advance(249ms); + result.test_u32_eq("did not retransmit before the capped timeout", op, 2); + cb->advance(1ms); + result.test_u32_eq("third retransmission ran", op, 3); + + // timeout stays capped at 250ms + cb->advance(249ms); + result.test_u32_eq("did not retransmit before the capped timeout", op, 3); + cb->advance(1ms); + result.test_u32_eq("fourth retransmission ran", op, 4); + + // with no maximum retransmission count configured, the timer + // retransmits indefinitely at the capped timeout and never gives up + result.test_no_throw("timer never times out", [&] { + for(uint32_t i = 5; i <= 20; ++i) { + cb->advance(249ms); + result.test_u32_eq("did not retransmit before the capped timeout", op, i - 1); + cb->advance(1ms); + result.test_u32_eq("retransmission ran at the capped timeout", op, i); + } + }); + + result.test_is_true("timer is still armed", timer.retransmissions_armed()); + }), + + CHECK("retransmission timer eventually times out with an exception", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, {}, 2), cb); + + timer.start(op.callback()); + result.test_is_true("timer is armed", timer.retransmissions_armed()); + result.test_is_false("flight timer is not armed", timer.flight_timeout_armed()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + cb->advance(200ms); + result.test_u32_eq("second retransmission ran", op, 2); + + const auto early_final_timeout = cb->get_next_scheduled_operation(); + result.test_no_throw("early final timeout invocations do not exhaust budget", [&] { + early_final_timeout(); + early_final_timeout(); + early_final_timeout(); + }); + result.test_u32_eq("early invocations did not retransmit", op, 2); + + // The timer expires and throws even though no timeout handler + // was set. + result.test_throws( + "timer gave up after the maximum number of retransmissions", + "DTLS (post-)handshake message exchange timed out: maximum retransmissions exceeded", + [&] { cb->advance(250ms); }); + result.test_u32_eq("no further retransmission was emitted", op, 2); + result.test_is_false("timer is no longer armed after giving up", timer.retransmissions_armed()); + result.test_is_false("no next timeout after giving up", timer.next_timeout().has_value()); + + // A new flight can still be sent after the previous one timed + // out. The timeout handler set here persists across restarts and + // is only invoked when the retransmission budget is exhausted. + Timer_Operation timeout_op; + timer.set_timeout_handler(timeout_op.callback()); + timer.start(op.callback()); + result.test_is_true("timer is armed after restart", timer.retransmissions_armed()); + result.test_u32_eq("timeout handler not called while the timer is armed", timeout_op, 0); + + cb->advance(99ms); + result.test_u32_eq("did not retransmit before the initial timeout", op, 2); + result.test_u32_eq("timeout handler not called before the retransmission", timeout_op, 0); + cb->advance(1ms); + result.test_u32_eq("retransmission ran after the initial timeout", op, 3); + result.test_u32_eq("timeout handler not called on the retransmission", timeout_op, 0); + + cb->advance(200ms); + result.test_u32_eq("second retransmission ran", op, 4); + result.test_u32_eq("timeout handler not called on retransmissions", timeout_op, 0); + + result.test_throws( + "timer gave up again after the maximum number of retransmissions", + "DTLS (post-)handshake message exchange timed out: maximum retransmissions exceeded", + [&] { cb->advance(250ms); }); + result.test_u32_eq("timeout handler was called when the timer expired", timeout_op, 1); + result.test_u32_eq("no further retransmission was emitted", op, 4); + result.test_is_false("timer is no longer armed after giving up again", timer.retransmissions_armed()); + }), + + CHECK("restarting a retransmission timer resets the exponential backoff and replaces the operation", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation restarted_op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, {}, {}), cb); + + timer.start(op.callback()); + cb->advance(100ms); + cb->advance(200ms); + result.test_u32_eq("two retransmissions ran", op, 2); + result.test_is_true("timer is armed", timer.retransmissions_armed()); + + // restart (with a new operation) while the backed-off timer (250ms) is still pending + timer.start(restarted_op.callback()); + result.test_is_true("timer is armed after restart", timer.retransmissions_armed()); + + cb->advance(99ms); + result.test_u32_eq("did not retransmit before the initial timeout", restarted_op, 0); + cb->advance(1ms); + result.test_u32_eq("retransmission ran after the reset initial timeout", restarted_op, 1); + + // backoff starts over: 100ms -> 200ms + cb->advance(199ms); + result.test_u32_eq("did not retransmit before the doubled timeout", restarted_op, 1); + cb->advance(1ms); + result.test_u32_eq("retransmission ran after the reset doubled timeout", restarted_op, 2); + + result.test_u32_eq("previous operation was never invoked again", op, 2); + result.test_is_true("timer is still armed", timer.retransmissions_armed()); + }), + + CHECK("destroying a running retransmission timer stops further retransmissions", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation timeout_op; + + { + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 500ms, {}), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + result.test_is_true("retransmission timer is armed", timer.retransmissions_armed()); + result.test_is_true("flight timer is armed", timer.flight_timeout_armed()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + result.test_is_true("retransmission timer is still armed", timer.retransmissions_armed()); + result.test_u64_eq( + "next timeout before the timer is destroyed", timer.next_timeout().value_or(-1ms).count(), 200); + result.test_u32_eq("timeout handler not called while the timer is armed", timeout_op, 0); + } + + result.test_no_throw("neither timer fires after the timer was destroyed", [&] { cb->advance(1000ms); }); + result.test_u32_eq("no further retransmissions ran", op, 1); + result.test_u32_eq("timeout handler not called after the timer was destroyed", timeout_op, 0); + }), + + CHECK("cancelling a running retransmission timer stops further retransmissions", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation timeout_op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, {}, {}), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + result.test_is_true("timer is armed", timer.retransmissions_armed()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + result.test_is_true("timer is still armed", timer.retransmissions_armed()); + result.test_u32_eq("timeout handler not called while the timer is armed", timeout_op, 0); + + timer.stop_retransmissions(); + result.test_is_false("timer is no longer armed", timer.retransmissions_armed()); + result.test_is_false("no next timeout after stopping the retransmissions", + timer.next_timeout().has_value()); + + cb->advance(1000ms); + result.test_u32_eq("no further retransmissions ran", op, 1); + result.test_u32_eq("timeout handler not called after cancellation", timeout_op, 0); + + // restarting after a cancel starts with the initial timeout again + timer.start(op.callback()); + result.test_is_true("timer is armed after restart", timer.retransmissions_armed()); + + cb->advance(99ms); + result.test_u32_eq("did not retransmit before the initial timeout", op, 1); + cb->advance(1ms); + result.test_u32_eq("retransmission ran after the initial timeout", op, 2); + result.test_u32_eq("timeout handler still not called after the restart", timeout_op, 0); + }), + + CHECK("retransmission budget is exhausted before the flight timeout is reached", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation timeout_op; + + // Retransmission schedule: 100ms, 200ms, 250ms, 250ms (capped). + // The retransmission budget of 3 is exhausted after 800ms, well + // before the flight timeout of 1000ms is reached. + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 1000ms, 3), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + result.test_is_true("retransmission timer is armed", timer.retransmissions_armed()); + result.test_is_true("flight timer is armed", timer.flight_timeout_armed()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + cb->advance(200ms); + result.test_u32_eq("second retransmission ran", op, 2); + cb->advance(250ms); + result.test_u32_eq("third retransmission ran", op, 3); + result.test_is_true("retransmission timer is still armed", timer.retransmissions_armed()); + result.test_is_true("flight timer is still armed", timer.flight_timeout_armed()); + result.test_u64_eq("next timeout is the remaining retransmission timeout", + timer.next_timeout().value_or(-1ms).count(), + 250); + result.test_u32_eq("timeout handler not called on retransmissions", timeout_op, 0); + + result.test_throws( + "timer gave up when the retransmission budget was exhausted", + "DTLS (post-)handshake message exchange timed out: maximum retransmissions exceeded", + [&] { cb->advance(250ms); }); + result.test_u32_eq("timeout handler was called when the timer expired", timeout_op, 1); + result.test_u32_eq("no further retransmission was emitted", op, 3); + result.test_is_false("retransmission timer is no longer armed", timer.retransmissions_armed()); + result.test_is_false("flight timer was cancelled when the budget was exhausted", + timer.flight_timeout_armed()); + result.test_is_false("no next timeout after the budget was exhausted", timer.next_timeout().has_value()); + + // The flight timeout deadline is reached right now. It must not + // fire anymore because the timer already gave up. + result.test_no_throw("flight timer does not fire after the budget was exhausted", + [&] { cb->advance(200ms); }); + result.test_u32_eq("no further retransmission was emitted after giving up", op, 3); + result.test_u32_eq("timeout handler was called only once", timeout_op, 1); + }), + + CHECK("flight timeout fires while retransmissions are still ongoing", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation timeout_op; + + // Retransmission schedule: 100ms, 200ms, 250ms, ... The flight + // timeout of 350ms strikes between the second and third + // retransmission, long before the retransmission budget of 5 is + // exhausted. + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 350ms, 5), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + cb->advance(200ms); + result.test_u32_eq("second retransmission ran", op, 2); + + // The retransmissions did not push the flight timer's deadline. + result.test_is_true("flight timer is still armed", timer.flight_timeout_armed()); + result.test_is_true("retransmission timer is still armed", timer.retransmissions_armed()); + result.test_u64_eq( + "next timeout is the earlier flight timeout", timer.next_timeout().value_or(-1ms).count(), 50); + + cb->advance(49ms); + result.test_u32_eq("did not retransmit before the flight timeout", op, 2); + result.test_u32_eq("timeout handler not called before the flight timeout", timeout_op, 0); + + result.test_throws( + "timer gave up when the flight timeout was reached", + "DTLS (post-)handshake message exchange timed out: flight timeout exceeded", + [&] { cb->advance(1ms); }); + result.test_u32_eq("timeout handler was called when the flight timeout was reached", timeout_op, 1); + result.test_u32_eq("no further retransmission was emitted", op, 2); + result.test_is_false("retransmission timer was cancelled by the flight timeout", + timer.retransmissions_armed()); + result.test_is_false("flight timer is no longer armed", timer.flight_timeout_armed()); + result.test_is_false("no next timeout after the flight timeout", timer.next_timeout().has_value()); + + result.test_no_throw("no further timer activity after the flight timeout", [&] { cb->advance(1000ms); }); + result.test_u32_eq("no further retransmission was emitted after the flight timeout", op, 2); + result.test_u32_eq("timeout handler was called only once", timeout_op, 1); + }), + + CHECK("flight timeout fires before the first retransmission", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation timeout_op; + + // The flight timeout of 50ms is shorter than the initial + // retransmission timeout of 100ms. + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 50ms, 3), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + result.test_is_true("retransmission timer is armed", timer.retransmissions_armed()); + result.test_is_true("flight timer is armed", timer.flight_timeout_armed()); + + // Prematurely invoking the flight timer's operation re-arms it + // for the remaining time instead of firing it. + cb->set_clock_forward(10ms); + const auto premature_flight_timeout = cb->get_next_scheduled_operation(); + result.test_no_throw("premature flight timeout invocation", [&] { premature_flight_timeout(); }); + result.test_u32_eq("premature invocation did not give up", op, 0); + result.test_u32_eq("premature invocation did not call the timeout handler", timeout_op, 0); + result.test_is_true("flight timer is still armed after premature invocation", + timer.flight_timeout_armed()); + result.test_is_true("retransmission timer is still armed after premature invocation", + timer.retransmissions_armed()); + result.test_u64_eq("next timeout still targets the original flight deadline", + timer.next_timeout().value_or(-1ms).count(), + 40); + const auto op_count_after_premature = cb->deferred_op_count(); + premature_flight_timeout(); + result.test_sz_eq("duplicate premature invocation did not schedule again", + cb->deferred_op_count(), + op_count_after_premature); + + cb->advance(39ms); + result.test_u32_eq("did not give up before the flight timeout", op, 0); + + result.test_throws( + "flight timeout fired at the originally scheduled deadline", + "DTLS (post-)handshake message exchange timed out: flight timeout exceeded", + [&] { cb->advance(1ms); }); + result.test_u32_eq("timeout handler was called when the flight timeout was reached", timeout_op, 1); + result.test_u32_eq("no retransmission was emitted at all", op, 0); + result.test_is_false("retransmission timer was cancelled by the flight timeout", + timer.retransmissions_armed()); + result.test_is_false("flight timer is no longer armed", timer.flight_timeout_armed()); + + result.test_no_throw("no further timer activity after the flight timeout", [&] { cb->advance(1000ms); }); + }), + + CHECK("without a retransmission limit, the flight timeout bounds the patience", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation timeout_op; + + // Retransmission schedule: 100ms, 200ms, 250ms, 250ms, ... The + // flight timeout of 450ms strikes between the second and third + // retransmission. Without a retransmission limit, the flight + // timer is the only bound on the exchange's patience. + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 450ms, {}), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + cb->advance(200ms); + result.test_u32_eq("second retransmission ran", op, 2); + result.test_is_true("retransmission timer is still armed", timer.retransmissions_armed()); + result.test_is_true("flight timer is still armed", timer.flight_timeout_armed()); + + cb->advance(149ms); + result.test_u32_eq("did not retransmit before the flight timeout", op, 2); + result.test_u64_eq( + "one millisecond before the flight timeout", timer.next_timeout().value_or(-1ms).count(), 1); + + result.test_throws( + "timer gave up when the flight timeout was reached", + "DTLS (post-)handshake message exchange timed out: flight timeout exceeded", + [&] { cb->advance(1ms); }); + result.test_u32_eq("timeout handler was called when the flight timeout was reached", timeout_op, 1); + result.test_u32_eq("no further retransmission was emitted", op, 2); + result.test_is_false("retransmission timer was cancelled by the flight timeout", + timer.retransmissions_armed()); + result.test_is_false("flight timer is no longer armed", timer.flight_timeout_armed()); + + result.test_no_throw("no further timer activity after the flight timeout", [&] { cb->advance(1000ms); }); + result.test_u32_eq("no further retransmission was emitted after the flight timeout", op, 2); + }), + + CHECK("stopping retransmissions does not affect the flight timer", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation timeout_op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 350ms, 3), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + result.test_is_true("flight timer is armed", timer.flight_timeout_armed()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + + timer.stop_retransmissions(); + result.test_is_false("retransmission timer is no longer armed", timer.retransmissions_armed()); + result.test_is_true("flight timer is still armed", timer.flight_timeout_armed()); + result.test_u64_eq( + "next timeout is the remaining flight timeout", timer.next_timeout().value_or(-1ms).count(), 250); + + // The cancelled retransmission timer does not fire anymore. + result.test_no_throw("cancelled retransmission timer does not fire", [&] { cb->advance(200ms); }); + result.test_u32_eq("no retransmission after stopping", op, 1); + result.test_u32_eq("timeout handler not called by the cancelled retransmission timer", timeout_op, 0); + + // The flight timer fires 350ms after the flight was sent, not + // 350ms after the retransmissions were stopped. + cb->advance(49ms); + result.test_u32_eq("did not give up before the flight timeout", op, 1); + result.test_u64_eq( + "one millisecond before the flight timeout", timer.next_timeout().value_or(-1ms).count(), 1); + result.test_throws( + "flight timeout fired at the deadline of the original flight", + "DTLS (post-)handshake message exchange timed out: flight timeout exceeded", + [&] { cb->advance(1ms); }); + result.test_u32_eq("timeout handler was called when the flight timeout was reached", timeout_op, 1); + result.test_is_false("retransmission timer is no longer armed", timer.retransmissions_armed()); + result.test_is_false("flight timer is no longer armed", timer.flight_timeout_armed()); + + result.test_no_throw("no further timer activity after the flight timeout", [&] { cb->advance(1000ms); }); + }), + + CHECK("restarting the timer re-arms the flight timer with a fresh budget", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation restarted_op; + Timer_Operation timeout_op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 280ms, {}), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + + timer.stop_retransmissions(); + result.test_is_true("flight timer is still armed", timer.flight_timeout_armed()); + + // Restarting while the previous flight timer is still armed + // replaces it with a fresh budget instead of extending it. + cb->advance(150ms); + timer.start(restarted_op.callback()); + result.test_is_true("retransmission timer is armed after the restart", timer.retransmissions_armed()); + result.test_is_true("flight timer is armed after the restart", timer.flight_timeout_armed()); + result.test_u64_eq("next timeout is the restart's initial retransmission timeout", + timer.next_timeout().value_or(-1ms).count(), + 100); + + // The previous flight timer's deadline (280ms after the first + // start) passes without firing. + cb->advance(50ms); + result.test_u32_eq("previous flight timer's deadline passed without firing", timeout_op, 0); + result.test_u32_eq("restarted operation did not run yet", restarted_op, 0); + + cb->advance(50ms); + result.test_u32_eq("retransmission ran after the restart's initial timeout", restarted_op, 1); + result.test_u32_eq("previous operation was never invoked again", op, 1); + result.test_is_true("flight timer is still armed", timer.flight_timeout_armed()); + result.test_u64_eq( + "next timeout is the restarted flight timeout", timer.next_timeout().value_or(-1ms).count(), 180); + + // The new flight timer fires 280ms after the restart, not 280ms + // after the original start. + cb->advance(179ms); + result.test_u32_eq("did not give up before the restarted flight timeout", restarted_op, 1); + result.test_throws( + "flight timeout fired at the deadline of the restarted flight", + "DTLS (post-)handshake message exchange timed out: flight timeout exceeded", + [&] { cb->advance(1ms); }); + result.test_u32_eq("timeout handler was called when the flight timeout was reached", timeout_op, 1); + result.test_u32_eq("no further retransmission was emitted", restarted_op, 1); + result.test_is_false("retransmission timer is no longer armed", timer.retransmissions_armed()); + result.test_is_false("flight timer is no longer armed", timer.flight_timeout_armed()); + + result.test_no_throw("no further timer activity after the flight timeout", [&] { cb->advance(1000ms); }); + }), + + CHECK("cancelling the timer disarms both the retransmission and the flight timer", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation timeout_op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 300ms, {}), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + result.test_is_true("retransmission timer is armed", timer.retransmissions_armed()); + result.test_is_true("flight timer is armed", timer.flight_timeout_armed()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + + timer.cancel(); + result.test_is_false("retransmission timer is no longer armed", timer.retransmissions_armed()); + result.test_is_false("flight timer is no longer armed", timer.flight_timeout_armed()); + result.test_is_false("no next timeout after the cancellation", timer.next_timeout().has_value()); + + result.test_no_throw("neither timer fires after the timer was cancelled", [&] { cb->advance(1000ms); }); + result.test_u32_eq("no further retransmission was emitted", op, 1); + result.test_u32_eq("timeout handler not called after cancellation", timeout_op, 0); + }), + + CHECK("cancelling after stopping the retransmissions also disarms the flight timer", + [&](Test::Result& result) { + auto cb = std::make_shared(); + Timer_Operation op; + Timer_Operation timeout_op; + + RetransmissionTimer timer(Retransmission_Test_Policy(100ms, 250ms, 300ms, {}), cb); + + timer.start(op.callback()); + timer.set_timeout_handler(timeout_op.callback()); + + cb->advance(100ms); + result.test_u32_eq("first retransmission ran", op, 1); + + timer.stop_retransmissions(); + result.test_is_false("retransmission timer is no longer armed", timer.retransmissions_armed()); + result.test_is_true("flight timer is still armed", timer.flight_timeout_armed()); + result.test_u64_eq( + "next timeout is the remaining flight timeout", timer.next_timeout().value_or(-1ms).count(), 200); + + timer.cancel(); + result.test_is_false("flight timer is no longer armed after the cancellation", + timer.flight_timeout_armed()); + result.test_is_false("no next timeout after the cancellation", timer.next_timeout().has_value()); + + result.test_no_throw("neither timer fires after the timer was cancelled", [&] { cb->advance(1000ms); }); + result.test_u32_eq("no further retransmission was emitted", op, 1); + result.test_u32_eq("timeout handler not called after cancellation", timeout_op, 0); + }), + }; +} + +} // namespace + +BOTAN_REGISTER_TEST_FN("tls", "dtls_timers", singleshot_timer, retransmission_timer); + +} // namespace Botan_Tests + +#endif diff --git a/src/tests/test_tls_protocol_version.cpp b/src/tests/test_tls_protocol_version.cpp index ca429c4f90c..0504b07ccaa 100644 --- a/src/tests/test_tls_protocol_version.cpp +++ b/src/tests/test_tls_protocol_version.cpp @@ -18,8 +18,8 @@ namespace Botan_Tests { #define BOTAN_PROVIDES_SOME_TLS_VERSION #endif - #if defined(BOTAN_HAS_TLS_12) /* DTLS 1.2 is not split off from TLS 1.2 */ - #define BOTAN_PROVIDES_SOME_DTLS_VERSION // DTLS 1.3 is not yet implemented + #if defined(BOTAN_HAS_TLS_12) || defined(BOTAN_HAS_DTLS_13) /* DTLS 1.2 is not split off from TLS 1.2 */ + #define BOTAN_PROVIDES_SOME_DTLS_VERSION #endif namespace { @@ -37,7 +37,9 @@ namespace TLS = Botan::TLS; } [[maybe_unused]] TLS::Protocol_Version latest_dtls_version_in_this_build() { - #if defined(BOTAN_HAS_TLS_12) + #if defined(BOTAN_HAS_DTLS_13) + return TLS::Protocol_Version::DTLS_V13; + #elif defined(BOTAN_HAS_TLS_12) return TLS::Protocol_Version::DTLS_V12; #else throw Test_Error("No DTLS in this build, some #ifdef issue in the test code?"); diff --git a/src/tests/unit_tls.cpp b/src/tests/unit_tls.cpp index 1c9e2ac9ca8..f911a5d6fb3 100644 --- a/src/tests/unit_tls.cpp +++ b/src/tests/unit_tls.cpp @@ -1607,6 +1607,8 @@ class TLS_Unit_Tests final : public Test { std::optional expected_version; // nullopt => handshake must fail }; + // The #if inside the initializer breaks clang-format's layout + // clang-format off const auto cases = std::array{ Case{ .name = "Client downgrade TLS 1.3 to 1.2", @@ -1637,7 +1639,38 @@ class TLS_Unit_Tests final : public Test { .expected_version = std::nullopt, }, + #if defined(BOTAN_HAS_DTLS_13) + Case{ + .name = "Client downgrade DTLS 1.3 to 1.2", + .client_versions = {PV::DTLS_V12, PV::DTLS_V13}, + .server_versions = {PV::DTLS_V12}, + .offer_version = PV::DTLS_V13, + .expected_version = PV::DTLS_V12, + }, + Case{ + .name = "Server downgrade DTLS 1.3 to 1.2", + .client_versions = {PV::DTLS_V12}, + .server_versions = {PV::DTLS_V12, PV::DTLS_V13}, + .offer_version = PV::DTLS_V12, + .expected_version = PV::DTLS_V12, + }, + Case{ + .name = "No shared version (client TLS 1.3 only)", + .client_versions = {PV::DTLS_V13}, + .server_versions = {PV::DTLS_V12}, + .offer_version = PV::DTLS_V13, + .expected_version = std::nullopt, + }, + Case{ + .name = "No shared version (server TLS 1.3 only)", + .client_versions = {PV::DTLS_V12}, + .server_versions = {PV::DTLS_V13}, + .offer_version = PV::DTLS_V12, + .expected_version = std::nullopt, + }, + #endif }; + // clang-format on const auto make_policy = [&](std::span versions) { auto policy = std::make_shared();