From 540fbda4599e8739e63610e8dd36d8c5d63f5b2b Mon Sep 17 00:00:00 2001 From: crimson-knight Date: Sun, 6 Dec 2026 06:35:49 -0500 Subject: [PATCH 1/5] Share the server's ClientHello checks and parameter choice Move check_client_hello, check_second_client_hello and the choice of cipher suite, group, ALPN protocol and server name out of TLS::ServerHandshake into TLS::NegotiateParametersFromClientHello, so the QUIC server handshake can call the same code. The TLS server applies the client's record_size_limit itself, as before; its behavior is unchanged. --- src/beryl/tls.cr | 1 + .../negotiate_parameters_from_client_hello.cr | 197 ++++++++++++++++++ src/beryl/tls/server_handshake.cr | 193 ++--------------- 3 files changed, 213 insertions(+), 178 deletions(-) create mode 100644 src/beryl/tls/negotiate_parameters_from_client_hello.cr diff --git a/src/beryl/tls.cr b/src/beryl/tls.cr index 8080ca6..5e26654 100644 --- a/src/beryl/tls.cr +++ b/src/beryl/tls.cr @@ -18,6 +18,7 @@ require "./tls/session_ticket" require "./tls/context" require "./tls/handshake_outcome" require "./tls/client_handshake" +require "./tls/negotiate_parameters_from_client_hello" require "./tls/server_handshake" require "./tls/socket" diff --git a/src/beryl/tls/negotiate_parameters_from_client_hello.cr b/src/beryl/tls/negotiate_parameters_from_client_hello.cr new file mode 100644 index 0000000..188caa5 --- /dev/null +++ b/src/beryl/tls/negotiate_parameters_from_client_hello.cr @@ -0,0 +1,197 @@ +require "./messages/handshake_messages" +require "./messages/extension_codec" +require "./context" + +module Beryl::TLS + # :nodoc: + # + # The checks a server makes on a ClientHello and the parameters it + # chooses from one: cipher suite, key exchange group and the client's + # share for it, ALPN protocol, server name. Both the TLS server handshake + # and the QUIC one (`Beryl::QUIC::ServerHandshake`) use it, so the two + # can never choose differently. One instance serves one handshake: it + # asks the ALPN chooser once and keeps the answer for a second + # ClientHello. + class NegotiateParametersFromClientHello + alias ExtensionCodec = Messages::ExtensionCodec + + # The choices made from one ClientHello. + record Selection, + cipher_suite : CipherSuite, + group : NamedGroup, + client_key_share : Bytes?, + alpn_protocol : String?, + server_name : String?, + peer_record_size_limit : Int32? + + @list_of_alpn_protocols_to_offer : Array(String)? = nil + + def initialize(@context : Context::Server) + end + + # The checks on any ClientHello (§4.1.2, §4.2, §9.2). + def check_client_hello(client_hello : Messages::ClientHello) : Nil + # SSL 3.0 and older are never negotiated (Appendix D.5), so such a + # legacy_version is no TLS 1.3 ClientHello. + if client_hello.legacy_version < ProtocolVersion::TLS_1_0 + raise Error.new("a ClientHello with legacy_version #{client_hello.legacy_version}", AlertDescription::ProtocolVersion) + end + versions_contents = client_hello.extension(ExtensionType::SupportedVersions) + unless versions_contents && ExtensionCodec.decode_client_supported_versions(versions_contents).includes?(ProtocolVersion::TLS_1_3) + raise Error.new("the client does not offer TLS 1.3", AlertDescription::ProtocolVersion) + end + unless client_hello.legacy_compression_methods == Bytes[0] + raise Error.new("a TLS 1.3 ClientHello with compression methods other than null", AlertDescription::IllegalParameter) + end + list_of_extensions = client_hello.list_of_extensions + list_of_extensions.each_with_index do |extension, index| + if extension.type_value == ExtensionType::PreSharedKey.value && index != list_of_extensions.size - 1 + raise Error.new("pre_shared_key is not the last extension", AlertDescription::IllegalParameter) + end + end + has_key_share = client_hello.has_extension?(ExtensionType::KeyShare) + has_groups = client_hello.has_extension?(ExtensionType::SupportedGroups) + if has_key_share != has_groups + raise Error.new("key_share and supported_groups must come together", AlertDescription::MissingExtension) + end + if client_hello.has_extension?(ExtensionType::PreSharedKey) && !client_hello.has_extension?(ExtensionType::PskKeyExchangeModes) + raise Error.new("pre_shared_key without psk_key_exchange_modes", AlertDescription::MissingExtension) + end + if !client_hello.has_extension?(ExtensionType::PreSharedKey) && !client_hello.has_extension?(ExtensionType::SignatureAlgorithms) + raise Error.new("no signature_algorithms", AlertDescription::MissingExtension) + end + raise Error.new("no key_share: Beryl requires (EC)DHE", AlertDescription::MissingExtension) unless has_key_share + # Decoding checks each list's structure. + client_hello.extension(ExtensionType::SignatureAlgorithms).try { |contents| ExtensionCodec.decode_u16_list(contents) } + client_hello.extension(ExtensionType::SignatureAlgorithmsCert).try { |contents| ExtensionCodec.decode_u16_list(contents) } + client_hello.extension(ExtensionType::PskKeyExchangeModes).try { |contents| ExtensionCodec.decode_psk_modes(contents) } + client_hello.extension(ExtensionType::ServerName).try { |contents| ExtensionCodec.decode_server_name(contents) } + end + + # The second ClientHello must be the first with the changes §4.1.2 + # allows: a new key share, the cookie, no early_data, new binders. + def check_second_client_hello(first : Messages::ClientHello, second : Messages::ClientHello) : Nil + unless first.random == second.random && first.legacy_session_id == second.legacy_session_id && + first.list_of_cipher_suites == second.list_of_cipher_suites + raise Error.new("the second ClientHello changes more than the HelloRetryRequest allows", AlertDescription::IllegalParameter) + end + if second.has_extension?(ExtensionType::EarlyData) + raise Error.new("early_data in the second ClientHello", AlertDescription::IllegalParameter) + end + if second.has_extension?(ExtensionType::Cookie) + raise Error.new("a cookie the server did not send", AlertDescription::IllegalParameter) + end + unless first.legacy_version == second.legacy_version && first.legacy_compression_methods == second.legacy_compression_methods + raise Error.new("the second ClientHello changes more than the HelloRetryRequest allows", AlertDescription::IllegalParameter) + end + # The same extensions in the same order and with the same contents, + # apart from the changes §4.1.2 allows: a new key_share, pre_shared_key + # recomputed or dropped, early_data dropped, padding resized. + unless comparable_extensions(first) == comparable_extensions(second) + raise Error.new("the second ClientHello changes its extensions beyond what the HelloRetryRequest allows", AlertDescription::IllegalParameter) + end + end + + private def comparable_extensions(client_hello : Messages::ClientHello) : Array({UInt16, Bytes}) + list = [] of {UInt16, Bytes} + client_hello.list_of_extensions.each do |extension| + case extension.type? + when ExtensionType::PreSharedKey, ExtensionType::EarlyData, ExtensionType::Padding + next + when ExtensionType::KeyShare + list << {extension.type_value, Bytes.empty} + else + list << {extension.type_value, extension.contents} + end + end + list + end + + # The suite, group, ALPN and name from *client_hello*. When + # *previous* is given (the second ClientHello), its suite and group + # are kept. + def select_parameters(client_hello : Messages::ClientHello, previous : Selection?) : Selection + cipher_suite = if previous + previous.cipher_suite + else + @context.list_of_cipher_suites.find { |suite| client_hello.list_of_cipher_suites.includes?(suite.value) } || + raise Error.new("no cipher suite in common", AlertDescription::HandshakeFailure) + end + unless client_hello.list_of_cipher_suites.includes?(cipher_suite.value) + raise Error.new("the second ClientHello drops the selected suite", AlertDescription::IllegalParameter) + end + + list_of_client_groups = ExtensionCodec.decode_u16_list(client_hello.extension(ExtensionType::SupportedGroups) || Bytes.empty) + # A set, so every share is checked against the groups in linear time. + client_group_values = list_of_client_groups.to_set + list_of_shares = ExtensionCodec.decode_client_key_shares(client_hello.extension(ExtensionType::KeyShare) || Bytes.empty) + list_of_shares.each do |share| + unless client_group_values.includes?(share.group_value) + raise Error.new("a key share for group #{share.group_value}, which supported_groups does not list", AlertDescription::IllegalParameter) + end + end + group, share = if previous + entry = list_of_shares.find { |candidate| candidate.group_value == previous.group.value } + unless entry && list_of_shares.size == 1 + raise Error.new("the second ClientHello must carry one share, for #{previous.group}", AlertDescription::IllegalParameter) + end + {previous.group, entry.key_exchange} + else + choose_group(client_group_values, list_of_shares) + end + + alpn_protocol = nil + if contents = client_hello.extension(ExtensionType::ApplicationLayerProtocolNegotiation) + list_of_offered = ExtensionCodec.decode_protocol_names(contents) + list_of_server_protocols = list_of_alpn_protocols_to_offer + unless list_of_server_protocols.empty? + alpn_protocol = list_of_server_protocols.find { |protocol| list_of_offered.includes?(protocol) } || + raise Error.new("no ALPN protocol in common", AlertDescription::NoApplicationProtocol) + end + end + server_name = client_hello.extension(ExtensionType::ServerName).try { |contents| ExtensionCodec.decode_server_name(contents) } + record_size_limit = client_hello.extension(ExtensionType::RecordSizeLimit).try { |contents| ExtensionCodec.decode_record_size_limit(contents) } + Selection.new(cipher_suite, group, share, alpn_protocol, server_name, record_size_limit) + end + + # The ALPN protocols this handshake selects from, in order of + # preference: what `Context::Server#alpn_protocol_chooser` returns, asked + # once per handshake (a second ClientHello repeats the first one's ALPN + # list), or `list_of_alpn_protocols` when no chooser is set. A chooser + # that raises ends the handshake with internal_error. + private def list_of_alpn_protocols_to_offer : Array(String) + @list_of_alpn_protocols_to_offer ||= if chooser = @context.alpn_protocol_chooser + begin + chooser.call + rescue error + raise Error.new("the ALPN protocol chooser raised: #{error.message}", AlertDescription::InternalError) + end + else + @context.list_of_alpn_protocols + end + end + + # The group for the first ClientHello and the client's share for it, or + # nil for the share when a HelloRetryRequest must ask for one. + # + # The server's order decides. When the first of its groups that the + # client lists is post-quantum, it is chosen even without a share. Otherwise + # the first of its groups the client sent a share for is chosen, which saves + # a round trip, and only when there is none does the first group the client + # lists get a HelloRetryRequest. + private def choose_group(client_group_values : Set(UInt16), list_of_shares : Array(ExtensionCodec::KeyShareEntry)) : {NamedGroup, Bytes?} + first_supported_group = @context.list_of_groups.find { |candidate| client_group_values.includes?(candidate.value) } || + raise Error.new("no key exchange group in common", AlertDescription::HandshakeFailure) + share_by_group_value = list_of_shares.to_h { |entry| {entry.group_value, entry.key_exchange} } + if first_supported_group.post_quantum? + return {first_supported_group, share_by_group_value[first_supported_group.value]?} + end + shared_group = @context.list_of_groups.find { |candidate| share_by_group_value.has_key?(candidate.value) } + if shared_group + {shared_group, share_by_group_value[shared_group.value]} + else + {first_supported_group, nil} + end + end + end +end diff --git a/src/beryl/tls/server_handshake.cr b/src/beryl/tls/server_handshake.cr index 05196b8..4145ce4 100644 --- a/src/beryl/tls/server_handshake.cr +++ b/src/beryl/tls/server_handshake.cr @@ -5,6 +5,7 @@ require "./transcript_hash" require "./context" require "./handshake_outcome" require "./handshake_secrets" +require "./negotiate_parameters_from_client_hello" module Beryl::TLS # The server side of a TLS 1.3 handshake (RFC 9846 §2, §4), run over a @@ -28,22 +29,15 @@ module Beryl::TLS identity_index : Int32, list_of_peer_certificates : Array(Certificates::Certificate) - # The choices made from one ClientHello. - private record Selection, - cipher_suite : CipherSuite, - group : NamedGroup, - client_key_share : Bytes?, - alpn_protocol : String?, - server_name : String?, - peer_record_size_limit : Int32? + alias Selection = NegotiateParametersFromClientHello::Selection @transcript = TranscriptHash.new @has_sent_change_cipher_spec = false - @list_of_alpn_protocols_to_offer : Array(String)? = nil @secrets = HandshakeSecrets.new def initialize(@record_layer : RecordLayer, @context : Context::Server) @randomness = @context.randomness + @negotiation = NegotiateParametersFromClientHello.new(@context) end # Runs the handshake. Every secret it derived and does not hand on is @@ -65,8 +59,8 @@ module Beryl::TLS @record_layer.is_change_cipher_spec_allowed = true expect_type(client_hello_message, HandshakeType::ClientHello) client_hello = Messages::ClientHello.decode(Messages.unwrap(client_hello_message)[1]) - check_client_hello(client_hello) - selection = select_parameters(client_hello, nil) + @negotiation.check_client_hello(client_hello) + selection = select_parameters_and_record_size_limit(client_hello, nil) # The certificate for the name the client asked for. A second # ClientHello repeats the first one's server_name, so this holds for # both; a name the server does not serve is refused before any reply. @@ -96,9 +90,9 @@ module Beryl::TLS second_message = @record_layer.read_handshake_message expect_type(second_message, HandshakeType::ClientHello) second_hello = Messages::ClientHello.decode(Messages.unwrap(second_message)[1]) - check_client_hello(second_hello) - check_second_client_hello(client_hello, second_hello) - second_selection = select_parameters(second_hello, selection) + @negotiation.check_client_hello(second_hello) + @negotiation.check_second_client_hello(client_hello, second_hello) + second_selection = select_parameters_and_record_size_limit(second_hello, selection) unless second_selection.client_key_share && second_selection.group == selection.group && second_selection.cipher_suite == selection.cipher_suite raise Error.new("the second ClientHello does not answer the HelloRetryRequest", AlertDescription::IllegalParameter) end @@ -326,172 +320,15 @@ module Beryl::TLS @has_sent_change_cipher_spec = true end - # The checks on any ClientHello (§4.1.2, §4.2, §9.2). - private def check_client_hello(client_hello : Messages::ClientHello) : Nil - # SSL 3.0 and older are never negotiated (Appendix D.5), so such a - # legacy_version is no TLS 1.3 ClientHello. - if client_hello.legacy_version < ProtocolVersion::TLS_1_0 - raise Error.new("a ClientHello with legacy_version #{client_hello.legacy_version}", AlertDescription::ProtocolVersion) - end - versions_contents = client_hello.extension(ExtensionType::SupportedVersions) - unless versions_contents && ExtensionCodec.decode_client_supported_versions(versions_contents).includes?(ProtocolVersion::TLS_1_3) - raise Error.new("the client does not offer TLS 1.3", AlertDescription::ProtocolVersion) - end - unless client_hello.legacy_compression_methods == Bytes[0] - raise Error.new("a TLS 1.3 ClientHello with compression methods other than null", AlertDescription::IllegalParameter) - end - list_of_extensions = client_hello.list_of_extensions - list_of_extensions.each_with_index do |extension, index| - if extension.type_value == ExtensionType::PreSharedKey.value && index != list_of_extensions.size - 1 - raise Error.new("pre_shared_key is not the last extension", AlertDescription::IllegalParameter) - end - end - has_key_share = client_hello.has_extension?(ExtensionType::KeyShare) - has_groups = client_hello.has_extension?(ExtensionType::SupportedGroups) - if has_key_share != has_groups - raise Error.new("key_share and supported_groups must come together", AlertDescription::MissingExtension) - end - if client_hello.has_extension?(ExtensionType::PreSharedKey) && !client_hello.has_extension?(ExtensionType::PskKeyExchangeModes) - raise Error.new("pre_shared_key without psk_key_exchange_modes", AlertDescription::MissingExtension) - end - if !client_hello.has_extension?(ExtensionType::PreSharedKey) && !client_hello.has_extension?(ExtensionType::SignatureAlgorithms) - raise Error.new("no signature_algorithms", AlertDescription::MissingExtension) - end - raise Error.new("no key_share: Beryl requires (EC)DHE", AlertDescription::MissingExtension) unless has_key_share - # Decoding checks each list's structure. - client_hello.extension(ExtensionType::SignatureAlgorithms).try { |contents| ExtensionCodec.decode_u16_list(contents) } - client_hello.extension(ExtensionType::SignatureAlgorithmsCert).try { |contents| ExtensionCodec.decode_u16_list(contents) } - client_hello.extension(ExtensionType::PskKeyExchangeModes).try { |contents| ExtensionCodec.decode_psk_modes(contents) } - client_hello.extension(ExtensionType::ServerName).try { |contents| ExtensionCodec.decode_server_name(contents) } - end - - # The second ClientHello must be the first with the changes §4.1.2 - # allows: a new key share, the cookie, no early_data, new binders. - private def check_second_client_hello(first : Messages::ClientHello, second : Messages::ClientHello) : Nil - unless first.random == second.random && first.legacy_session_id == second.legacy_session_id && - first.list_of_cipher_suites == second.list_of_cipher_suites - raise Error.new("the second ClientHello changes more than the HelloRetryRequest allows", AlertDescription::IllegalParameter) - end - if second.has_extension?(ExtensionType::EarlyData) - raise Error.new("early_data in the second ClientHello", AlertDescription::IllegalParameter) - end - if second.has_extension?(ExtensionType::Cookie) - raise Error.new("a cookie the server did not send", AlertDescription::IllegalParameter) - end - unless first.legacy_version == second.legacy_version && first.legacy_compression_methods == second.legacy_compression_methods - raise Error.new("the second ClientHello changes more than the HelloRetryRequest allows", AlertDescription::IllegalParameter) - end - # The same extensions in the same order and with the same contents, - # apart from the changes §4.1.2 allows: a new key_share, pre_shared_key - # recomputed or dropped, early_data dropped, padding resized. - unless comparable_extensions(first) == comparable_extensions(second) - raise Error.new("the second ClientHello changes its extensions beyond what the HelloRetryRequest allows", AlertDescription::IllegalParameter) - end - end - - private def comparable_extensions(client_hello : Messages::ClientHello) : Array({UInt16, Bytes}) - list = [] of {UInt16, Bytes} - client_hello.list_of_extensions.each do |extension| - case extension.type? - when ExtensionType::PreSharedKey, ExtensionType::EarlyData, ExtensionType::Padding - next - when ExtensionType::KeyShare - list << {extension.type_value, Bytes.empty} - else - list << {extension.type_value, extension.contents} - end - end - list - end - - # The suite, group, ALPN and name from *client_hello*. When - # *previous* is given (the second ClientHello), its suite and group - # are kept. - private def select_parameters(client_hello : Messages::ClientHello, previous : Selection?) : Selection - cipher_suite = if previous - previous.cipher_suite - else - @context.list_of_cipher_suites.find { |suite| client_hello.list_of_cipher_suites.includes?(suite.value) } || - raise Error.new("no cipher suite in common", AlertDescription::HandshakeFailure) - end - unless client_hello.list_of_cipher_suites.includes?(cipher_suite.value) - raise Error.new("the second ClientHello drops the selected suite", AlertDescription::IllegalParameter) - end - - list_of_client_groups = ExtensionCodec.decode_u16_list(client_hello.extension(ExtensionType::SupportedGroups) || Bytes.empty) - # A set, so every share is checked against the groups in linear time. - client_group_values = list_of_client_groups.to_set - list_of_shares = ExtensionCodec.decode_client_key_shares(client_hello.extension(ExtensionType::KeyShare) || Bytes.empty) - list_of_shares.each do |share| - unless client_group_values.includes?(share.group_value) - raise Error.new("a key share for group #{share.group_value}, which supported_groups does not list", AlertDescription::IllegalParameter) - end - end - group, share = if previous - entry = list_of_shares.find { |candidate| candidate.group_value == previous.group.value } - unless entry && list_of_shares.size == 1 - raise Error.new("the second ClientHello must carry one share, for #{previous.group}", AlertDescription::IllegalParameter) - end - {previous.group, entry.key_exchange} - else - choose_group(client_group_values, list_of_shares) - end - - alpn_protocol = nil - if contents = client_hello.extension(ExtensionType::ApplicationLayerProtocolNegotiation) - list_of_offered = ExtensionCodec.decode_protocol_names(contents) - list_of_server_protocols = list_of_alpn_protocols_to_offer - unless list_of_server_protocols.empty? - alpn_protocol = list_of_server_protocols.find { |protocol| list_of_offered.includes?(protocol) } || - raise Error.new("no ALPN protocol in common", AlertDescription::NoApplicationProtocol) - end - end - server_name = client_hello.extension(ExtensionType::ServerName).try { |contents| ExtensionCodec.decode_server_name(contents) } - record_size_limit = client_hello.extension(ExtensionType::RecordSizeLimit).try { |contents| ExtensionCodec.decode_record_size_limit(contents) } - if limit = record_size_limit + # Selects the parameters from *client_hello* (see + # `NegotiateParametersFromClientHello#select_parameters`) and fits the + # records this server writes to the client's record_size_limit. + private def select_parameters_and_record_size_limit(client_hello : Messages::ClientHello, previous : Selection?) : Selection + selection = @negotiation.select_parameters(client_hello, previous) + if limit = selection.peer_record_size_limit @record_layer.largest_outgoing_fragment_bytesize = Math.min(RecordLayer::LARGEST_FRAGMENT_BYTESIZE, limit - 1) end - Selection.new(cipher_suite, group, share, alpn_protocol, server_name, record_size_limit) - end - - # The ALPN protocols this handshake selects from, in order of - # preference: what `Context::Server#alpn_protocol_chooser` returns, asked - # once per handshake (a second ClientHello repeats the first one's ALPN - # list), or `list_of_alpn_protocols` when no chooser is set. A chooser - # that raises ends the handshake with internal_error. - private def list_of_alpn_protocols_to_offer : Array(String) - @list_of_alpn_protocols_to_offer ||= if chooser = @context.alpn_protocol_chooser - begin - chooser.call - rescue error - raise Error.new("the ALPN protocol chooser raised: #{error.message}", AlertDescription::InternalError) - end - else - @context.list_of_alpn_protocols - end - end - - # The group for the first ClientHello and the client's share for it, or - # nil for the share when a HelloRetryRequest must ask for one. - # - # The server's order decides. When the first of its groups that the - # client lists is post-quantum, it is chosen even without a share. Otherwise - # the first of its groups the client sent a share for is chosen, which saves - # a round trip, and only when there is none does the first group the client - # lists get a HelloRetryRequest. - private def choose_group(client_group_values : Set(UInt16), list_of_shares : Array(ExtensionCodec::KeyShareEntry)) : {NamedGroup, Bytes?} - first_supported_group = @context.list_of_groups.find { |candidate| client_group_values.includes?(candidate.value) } || - raise Error.new("no key exchange group in common", AlertDescription::HandshakeFailure) - share_by_group_value = list_of_shares.to_h { |entry| {entry.group_value, entry.key_exchange} } - if first_supported_group.post_quantum? - return {first_supported_group, share_by_group_value[first_supported_group.value]?} - end - shared_group = @context.list_of_groups.find { |candidate| share_by_group_value.has_key?(candidate.value) } - if shared_group - {shared_group, share_by_group_value[shared_group.value]} - else - {first_supported_group, nil} - end + selection end # Beryl never accepts 0-RTT. A client that sent early_data has its From 53a906e521325c02a775265723e69f30fc6b0a84 Mon Sep 17 00:00:00 2001 From: crimson-knight Date: Sun, 6 Dec 2026 06:35:53 -0500 Subject: [PATCH 2/5] Add Beryl::QUIC: RFC 9001 packet protection and a sans-IO server handshake - PacketProtection: initial secrets from the client's Destination Connection ID, packet protection under quic key/quic iv with into: forms, header protection masks (AES-ECB and ChaCha20 under quic hp), and key update under quic ku sharing the header protection key. - ServerHandshake: the TLS 1.3 server handshake over CRYPTO data per encryption level, with one HelloRetryRequest, ALPN required, the quic_transport_parameters extension both ways, an empty legacy_session_id, no 0-RTT, tickets or KeyUpdate, bounded buffering per level, and every derived secret wiped. - HandshakeError carries the alert and the QUIC error code. - QUIC.retry_integrity_tag for Retry packets. - Specs: every RFC 9001 Appendix A vector, key update, tampering, and the handshake end to end against a client built from Beryl's codecs. --- CHANGELOG.md | 22 ++ docs/tls.md | 21 ++ spec/beryl/quic/packet_protection_spec.cr | 337 +++++++++++++++++++ spec/beryl/quic/server_handshake_spec.cr | 336 +++++++++++++++++++ src/beryl.cr | 1 + src/beryl/quic.cr | 19 ++ src/beryl/quic/encryption_level.cr | 9 + src/beryl/quic/handshake_error.cr | 23 ++ src/beryl/quic/header_protection_key.cr | 108 ++++++ src/beryl/quic/installed_keys.cr | 10 + src/beryl/quic/packet_protection.cr | 186 +++++++++++ src/beryl/quic/retry_integrity_tag.cr | 26 ++ src/beryl/quic/server_handshake.cr | 381 ++++++++++++++++++++++ src/beryl/tls/protocol.cr | 55 ++-- 14 files changed, 1508 insertions(+), 26 deletions(-) create mode 100644 spec/beryl/quic/packet_protection_spec.cr create mode 100644 spec/beryl/quic/server_handshake_spec.cr create mode 100644 src/beryl/quic.cr create mode 100644 src/beryl/quic/encryption_level.cr create mode 100644 src/beryl/quic/handshake_error.cr create mode 100644 src/beryl/quic/header_protection_key.cr create mode 100644 src/beryl/quic/installed_keys.cr create mode 100644 src/beryl/quic/packet_protection.cr create mode 100644 src/beryl/quic/retry_integrity_tag.cr create mode 100644 src/beryl/quic/server_handshake.cr diff --git a/CHANGELOG.md b/CHANGELOG.md index 13d2a78..afaadcf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ ## Unreleased +- QUIC: `Beryl::QUIC`, the cryptographic half of QUIC version 1 (RFC 9001), + sans-IO, for a QUIC transport such as Mica's. + `PacketProtection` is one direction of one encryption level: the initial + pair a server derives from the client's Destination Connection ID, packet + protection under the `quic key` and `quic iv` labels (with `into:` forms + that write into the caller's storage), the 5-byte header protection mask + (AES-ECB or ChaCha20 under `quic hp`), and key update (`quic ku`), which + keeps the header protection key. `ServerHandshake` runs the TLS 1.3 + server handshake over CRYPTO data per encryption level and hands out the + Handshake and Application keys as `InstalledKeys`; it requires ALPN + (`no_application_protocol`) and the client's `quic_transport_parameters` + (`missing_extension`), refuses a non-empty `legacy_session_id` and a + KeyUpdate message, accepts no 0-RTT and issues no session tickets. + `HandshakeError` carries the alert and the QUIC error code + (CRYPTO_ERROR `0x0100` plus the alert, or PROTOCOL_VIOLATION). + `QUIC.retry_integrity_tag` computes the Retry Integrity Tag. Checked + against every packet in RFC 9001 Appendix A. +- TLS: the ClientHello checks and the choice of suite, group, ALPN protocol + and server name moved from `ServerHandshake` into + `NegotiateParametersFromClientHello`, which the TLS and QUIC servers + share, so the two choose alike. The TLS server behaves as before. + ## 0.2.8 (2026-12-05) One TLS listener for several sites: a server chooses its certificate by the diff --git a/docs/tls.md b/docs/tls.md index 5bae09b..fbd13c6 100644 --- a/docs/tls.md +++ b/docs/tls.md @@ -142,6 +142,27 @@ context.refuses_unrecognized_server_names = true # the default - `certified_key_for_server_name(name)` answers which key a name gets, for checks at boot. - A session ticket records the server name it was issued under and resumes only under that same name, so a ticket never carries a connection from one certificate to another. +## QUIC (RFC 9001) + +`Beryl::QUIC` carries the same TLS 1.3 server handshake in QUIC's CRYPTO frames, sans-IO, and protects QUIC packets. A transport (Mica's QUIC core, hosted by Amber) owns the UDP socket, the frames and the packet number spaces; Beryl owns every key, and hands out only objects that seal and open. + +```crystal +read_initial, write_initial = Beryl::QUIC::PacketProtection.initial_pair_for_server(client_destination_connection_id) +handshake = Beryl::QUIC::ServerHandshake.new(context, encoded_transport_parameters) +handshake.receive_crypto_data(Beryl::QUIC::EncryptionLevel::Initial, crypto_bytes) +handshake.take_crypto_data_to_send(Beryl::QUIC::EncryptionLevel::Initial) # ServerHello (or a HelloRetryRequest) +handshake.take_list_of_installed_keys # Handshake, then Application +handshake.take_crypto_data_to_send(Beryl::QUIC::EncryptionLevel::Handshake) # EncryptedExtensions to Finished +handshake.complete? # once the client's Finished verified +``` + +- The server chooses its suite, group, certificate by server name and ALPN protocol exactly as the TLS server does, from the same `Context::Server`: both call `NegotiateParametersFromClientHello`. +- ALPN is required: no agreed protocol ends with `no_application_protocol`. The client's `quic_transport_parameters` (extension 57) is required (`missing_extension`) and is exposed unparsed as `peer_transport_parameters`; the server's goes in its EncryptedExtensions. +- A non-empty `legacy_session_id`, Initial data left unread when the Handshake keys arrive, and Handshake data after the client's Finished are PROTOCOL_VIOLATION; every other failure is CRYPTO_ERROR `0x0100` plus the alert. `HandshakeError#transport_error_code` gives the code to close with. +- No session resumption, no 0-RTT, no session tickets, no client certificates (a context that asks for them is refused when the handshake is made), no KeyUpdate message (QUIC uses the key phase bit: `PacketProtection#next_generation`). +- Each encryption level buffers at most one incomplete message, no larger than `Limits#largest_handshake_message_bytesize`, refused from its header. +- Secrets: the handshake wipes everything it derives when it completes or fails (`wipe` for a handshake the transport abandons). `PacketProtection` copies the traffic secret it is given; `wipe` erases its key, IV and secret, and the header protection key once no generation shares it. + ## Limits Set through `Context#limits = Beryl::TLS::Limits.new(...)`; the defaults are the plan's (§4). diff --git a/spec/beryl/quic/packet_protection_spec.cr b/spec/beryl/quic/packet_protection_spec.cr new file mode 100644 index 0000000..5f289fe --- /dev/null +++ b/spec/beryl/quic/packet_protection_spec.cr @@ -0,0 +1,337 @@ +require "../../spec_helper" + +# RFC 9001 Appendix A, copied from https://www.rfc-editor.org/rfc/rfc9001.txt. +private module Rfc9001Appendix + DESTINATION_CONNECTION_ID = "8394c8f03e515708".hexbytes + + CLIENT_INITIAL_SECRET = "c00cf151ca5be075ed0ebfb5c80323c42d6b7db67881289af4008f1f6c357aea".hexbytes + CLIENT_KEY = "1f369613dd76d5467730efcbe3b1a22d".hexbytes + CLIENT_IV = "fa044b2f42a3fd3b46fb255c".hexbytes + CLIENT_HP = "9f50449e04a0e810283a1e9933adedd2".hexbytes + SERVER_INITIAL_SECRET = "3c199828fd139efd216c155ad844cc81fb82fa8d7446fa7d78be803acdda951b".hexbytes + SERVER_KEY = "cf3a5331653c364c88f0f379b6067e37".hexbytes + SERVER_IV = "0ac1493ca1905853b0bba03e".hexbytes + SERVER_HP = "c206b8d9b9f0f37644430b490eeaa314".hexbytes + INITIAL_SECRET = "7db5df06e7a69e432496adedb00851923595221596ae2ae9fb8115c1e9ed0a44".hexbytes + + # A.2: the client's unprotected header (packet number 2) and its mask. + CLIENT_INITIAL_HEADER = "c300000001088394c8f03e5157080000449e00000002".hexbytes + CLIENT_INITIAL_SAMPLE = "d1b1c98dd7689fb8ec11d242b123dc9b".hexbytes + CLIENT_INITIAL_MASK = "437b9aec36".hexbytes + # A.2: the CRYPTO frame, padded with PADDING frames to 1162 bytes. + CLIENT_INITIAL_CRYPTO_FRAME = <<-HEX.delete("\n").hexbytes + 060040f1010000ed0303ebf8fa56f12939b9584a3896472ec40bb863cfd3e868 + 04fe3a47f06a2b69484c00000413011302010000c000000010000e00000b6578 + 616d706c652e636f6dff01000100000a00080006001d00170018001000070005 + 04616c706e000500050100000000003300260024001d00209370b2c9caa47fba + baf4559fedba753de171fa71f50f1ce15d43e994ec74d748002b000302030400 + 0d0010000e0403050306030203080408050806002d00020101001c0002400100 + 3900320408ffffffffffffffff05048000ffff07048000ffff08011001048000 + 75300901100f088394c8f03e51570806048000ffff + HEX + CLIENT_INITIAL_PAYLOAD_BYTESIZE = 1162 + CLIENT_INITIAL_PROTECTED_PACKET = <<-HEX.delete("\n").hexbytes + c000000001088394c8f03e5157080000449e7b9aec34d1b1c98dd7689fb8ec11 + d242b123dc9bd8bab936b47d92ec356c0bab7df5976d27cd449f63300099f399 + 1c260ec4c60d17b31f8429157bb35a1282a643a8d2262cad67500cadb8e7378c + 8eb7539ec4d4905fed1bee1fc8aafba17c750e2c7ace01e6005f80fcb7df6212 + 30c83711b39343fa028cea7f7fb5ff89eac2308249a02252155e2347b63d58c5 + 457afd84d05dfffdb20392844ae812154682e9cf012f9021a6f0be17ddd0c208 + 4dce25ff9b06cde535d0f920a2db1bf362c23e596d11a4f5a6cf3948838a3aec + 4e15daf8500a6ef69ec4e3feb6b1d98e610ac8b7ec3faf6ad760b7bad1db4ba3 + 485e8a94dc250ae3fdb41ed15fb6a8e5eba0fc3dd60bc8e30c5c4287e53805db + 059ae0648db2f64264ed5e39be2e20d82df566da8dd5998ccabdae053060ae6c + 7b4378e846d29f37ed7b4ea9ec5d82e7961b7f25a9323851f681d582363aa5f8 + 9937f5a67258bf63ad6f1a0b1d96dbd4faddfcefc5266ba6611722395c906556 + be52afe3f565636ad1b17d508b73d8743eeb524be22b3dcbc2c7468d54119c74 + 68449a13d8e3b95811a198f3491de3e7fe942b330407abf82a4ed7c1b311663a + c69890f4157015853d91e923037c227a33cdd5ec281ca3f79c44546b9d90ca00 + f064c99e3dd97911d39fe9c5d0b23a229a234cb36186c4819e8b9c5927726632 + 291d6a418211cc2962e20fe47feb3edf330f2c603a9d48c0fcb5699dbfe58964 + 25c5bac4aee82e57a85aaf4e2513e4f05796b07ba2ee47d80506f8d2c25e50fd + 14de71e6c418559302f939b0e1abd576f279c4b2e0feb85c1f28ff18f58891ff + ef132eef2fa09346aee33c28eb130ff28f5b766953334113211996d20011a198 + e3fc433f9f2541010ae17c1bf202580f6047472fb36857fe843b19f5984009dd + c324044e847a4f4a0ab34f719595de37252d6235365e9b84392b061085349d73 + 203a4a13e96f5432ec0fd4a1ee65accdd5e3904df54c1da510b0ff20dcc0c77f + cb2c0e0eb605cb0504db87632cf3d8b4dae6e705769d1de354270123cb11450e + fc60ac47683d7b8d0f811365565fd98c4c8eb936bcab8d069fc33bd801b03ade + a2e1fbc5aa463d08ca19896d2bf59a071b851e6c239052172f296bfb5e724047 + 90a2181014f3b94a4e97d117b438130368cc39dbb2d198065ae3986547926cd2 + 162f40a29f0c3c8745c0f50fba3852e566d44575c29d39a03f0cda721984b6f4 + 40591f355e12d439ff150aab7613499dbd49adabc8676eef023b15b65bfc5ca0 + 6948109f23f350db82123535eb8a7433bdabcb909271a6ecbcb58b936a88cd4e + 8f2e6ff5800175f113253d8fa9ca8885c2f552e657dc603f252e1a8e308f76f0 + be79e2fb8f5d5fbbe2e30ecadd220723c8c0aea8078cdfcb3868263ff8f09400 + 54da48781893a7e49ad5aff4af300cd804a6b6279ab3ff3afb64491c85194aab + 760d58a606654f9f4400e8b38591356fbf6425aca26dc85244259ff2b19c41b9 + f96f3ca9ec1dde434da7d2d392b905ddf3d1f9af93d1af5950bd493f5aa731b4 + 056df31bd267b6b90a079831aaf579be0a39013137aac6d404f518cfd4684064 + 7e78bfe706ca4cf5e9c5453e9f7cfd2b8b4c8d169a44e55c88d4a9a7f9474241 + e221af44860018ab0856972e194cd934 + HEX + + # A.3: the server's header (packet number 1, two bytes) and its mask. + SERVER_INITIAL_HEADER = "c1000000010008f067a5502a4262b50040750001".hexbytes + SERVER_INITIAL_SAMPLE = "2cd0991cd25b0aac406a5816b6394100".hexbytes + SERVER_INITIAL_MASK = "2ec0d8356a".hexbytes + SERVER_INITIAL_PAYLOAD = <<-HEX.delete("\n").hexbytes + 02000000000600405a020000560303eefce7f7b37ba1d1632e96677825ddf739 + 88cfc79825df566dc5430b9a045a1200130100002e00330024001d00209d3c94 + 0d89690b84d08a60993c144eca684d1081287c834d5311bcf32bb9da1a002b00 + 020304 + HEX + SERVER_INITIAL_PROTECTED_PACKET = <<-HEX.delete("\n").hexbytes + cf000000010008f067a5502a4262b5004075c0d95a482cd0991cd25b0aac406a + 5816b6394100f37a1c69797554780bb38cc5a99f5ede4cf73c3ec2493a1839b3 + dbcba3f6ea46c5b7684df3548e7ddeb9c3bf9c73cc3f3bded74b562bfb19fb84 + 022f8ef4cdd93795d77d06edbb7aaf2f58891850abbdca3d20398c276456cbc4 + 2158407dd074ee + HEX + + # A.4: the Retry packet, its last 16 bytes the integrity tag. + RETRY_PACKET = "ff000000010008f067a5502a4262b5746f6b656e04a265ba2eff4d829058fb3f0f2496ba".hexbytes + + # A.5: a ChaCha20-Poly1305 short header packet. + CHACHA20_SECRET = "9ac312a7f877468ebe69422748ad00a15443f18203a07d6060f688f30f21632b".hexbytes + CHACHA20_KEY = "c6d98ff3441c3fe1b2182094f69caa2ed4b716b65488960a7a984979fb23e1c8".hexbytes + CHACHA20_IV = "e0459b3474bdd0e44a41c144".hexbytes + CHACHA20_HP = "25a282b9e82f06f21f488917a4fc8f1b73573685608597d0efcb076b0ab7a7a4".hexbytes + CHACHA20_KU = "1223504755036d556342ee9361d253421a826c9ecdf3c7148684b36b714881f9".hexbytes + CHACHA20_PACKET_NUMBER = 654_360_564_u64 + CHACHA20_NONCE = "e0459b3474bdd0e46d417eb0".hexbytes + CHACHA20_HEADER = "4200bff4".hexbytes + CHACHA20_PLAINTEXT = "01".hexbytes + CHACHA20_CIPHERTEXT = "655e5cd55c41f69080575d7999c25a5bfb".hexbytes + CHACHA20_SAMPLE = "5e5cd55c41f69080575d7999c25a5bfb".hexbytes + CHACHA20_MASK = "aefefe7d03".hexbytes + CHACHA20_PACKET = "4cfe4189655e5cd55c41f69080575d7999c25a5bfb".hexbytes +end + +# Seals *payload* behind *header* and applies header protection, as a QUIC +# transport does (RFC 9001 §5.4.1); the packet number is the header's last +# *packet_number_bytesize* bytes. +private def protect_packet(protection : Beryl::QUIC::PacketProtection, header : Bytes, packet_number : UInt64, + packet_number_bytesize : Int32, payload : Bytes) : Bytes + protected_payload = protection.seal(packet_number, header, payload) + packet = Bytes.new(header.size + protected_payload.size) + header.copy_to(packet) + protected_payload.copy_to(packet + header.size) + packet_number_offset = header.size - packet_number_bytesize + mask = protection.header_protection_mask(packet[packet_number_offset + 4, 16]) + is_long_header = packet[0] & 0x80 != 0 + packet[0] ^= mask[0] & (is_long_header ? 0x0f_u8 : 0x1f_u8) + packet_number_bytesize.times { |index| packet[packet_number_offset + index] ^= mask[1 + index] } + packet +end + +# Removes header protection from *packet*, whose packet number starts at +# *packet_number_offset*, and opens it. Returns the packet number and the +# payload, or nil when it fails authentication. +private def unprotect_packet(protection : Beryl::QUIC::PacketProtection, packet : Bytes, packet_number_offset : Int32) : {UInt64, Bytes}? + unprotected = packet.dup + mask = protection.header_protection_mask(unprotected[packet_number_offset + 4, 16]) + is_long_header = unprotected[0] & 0x80 != 0 + unprotected[0] ^= mask[0] & (is_long_header ? 0x0f_u8 : 0x1f_u8) + packet_number_bytesize = (unprotected[0] & 0x03) + 1 + packet_number = 0_u64 + packet_number_bytesize.times do |index| + unprotected[packet_number_offset + index] ^= mask[1 + index] + packet_number = (packet_number << 8) | unprotected[packet_number_offset + index] + end + header_bytesize = packet_number_offset + packet_number_bytesize + payload = protection.open(packet_number, unprotected[0, header_bytesize], unprotected[header_bytesize..]) + payload ? {packet_number, payload} : nil +end + +private def client_initial_payload : Bytes + payload = Bytes.new(Rfc9001Appendix::CLIENT_INITIAL_PAYLOAD_BYTESIZE) + Rfc9001Appendix::CLIENT_INITIAL_CRYPTO_FRAME.copy_to(payload) + payload +end + +describe Beryl::QUIC::PacketProtection do + describe "RFC 9001 Appendix A.1, keys" do + it "derives the initial secrets and their key, IV and header protection key" do + hash = Beryl::TLS::HashAlgorithm::SHA256 + initial_secret = hash.extract(Rfc9001Appendix::DESTINATION_CONNECTION_ID, salt: Beryl::QUIC::PacketProtection::INITIAL_SALT) + initial_secret.should eq(Rfc9001Appendix::INITIAL_SECRET) + Beryl::TLS::KeySchedule.expand_label(hash, initial_secret, "client in", Bytes.empty, 32).should eq(Rfc9001Appendix::CLIENT_INITIAL_SECRET) + Beryl::TLS::KeySchedule.expand_label(hash, initial_secret, "server in", Bytes.empty, 32).should eq(Rfc9001Appendix::SERVER_INITIAL_SECRET) + { + {Rfc9001Appendix::CLIENT_INITIAL_SECRET, Rfc9001Appendix::CLIENT_KEY, Rfc9001Appendix::CLIENT_IV, Rfc9001Appendix::CLIENT_HP}, + {Rfc9001Appendix::SERVER_INITIAL_SECRET, Rfc9001Appendix::SERVER_KEY, Rfc9001Appendix::SERVER_IV, Rfc9001Appendix::SERVER_HP}, + }.each do |secret, key, iv, hp| + Beryl::TLS::KeySchedule.expand_label(hash, secret, "quic key", Bytes.empty, 16).should eq(key) + Beryl::TLS::KeySchedule.expand_label(hash, secret, "quic iv", Bytes.empty, 12).should eq(iv) + Beryl::TLS::KeySchedule.expand_label(hash, secret, "quic hp", Bytes.empty, 16).should eq(hp) + end + end + + it "builds the server's pair from the client's Destination Connection ID: read with the client's keys, write with the server's" do + read_protection, write_protection = Beryl::QUIC::PacketProtection.initial_pair_for_server(Rfc9001Appendix::DESTINATION_CONNECTION_ID) + { + {read_protection, Rfc9001Appendix::CLIENT_KEY, Rfc9001Appendix::CLIENT_IV}, + {write_protection, Rfc9001Appendix::SERVER_KEY, Rfc9001Appendix::SERVER_IV}, + }.each do |protection, key, iv| + protection.cipher_suite.should eq(Beryl::TLS::CipherSuite::TLS_AES_128_GCM_SHA256) + header = "c3".hexbytes + # Packet number 0: the nonce is the IV itself. + expected = Beryl::Crypto::V1::AESGCM.new(key).encrypt("payload".to_slice, nonce: iv, associated_data: header) + protection.seal(0_u64, header, "payload".to_slice).should eq(expected) + end + # AES-ECB of the samples with each hp key (A.2 and A.3). + read_protection.header_protection_mask(Rfc9001Appendix::CLIENT_INITIAL_SAMPLE).should eq(Rfc9001Appendix::CLIENT_INITIAL_MASK) + write_protection.header_protection_mask(Rfc9001Appendix::SERVER_INITIAL_SAMPLE).should eq(Rfc9001Appendix::SERVER_INITIAL_MASK) + end + end + + describe "RFC 9001 Appendix A.2, client Initial" do + it "protects the client's payload into the published packet" do + client_protection = Beryl::QUIC::PacketProtection.new(Beryl::TLS::CipherSuite::TLS_AES_128_GCM_SHA256, Rfc9001Appendix::CLIENT_INITIAL_SECRET) + packet = protect_packet(client_protection, Rfc9001Appendix::CLIENT_INITIAL_HEADER, 2_u64, 4, client_initial_payload) + packet.should eq(Rfc9001Appendix::CLIENT_INITIAL_PROTECTED_PACKET) + end + + it "opens the published packet with the server's read protection" do + read_protection, _ = Beryl::QUIC::PacketProtection.initial_pair_for_server(Rfc9001Appendix::DESTINATION_CONNECTION_ID) + packet_number_offset = Rfc9001Appendix::CLIENT_INITIAL_HEADER.size - 4 + opened = unprotect_packet(read_protection, Rfc9001Appendix::CLIENT_INITIAL_PROTECTED_PACKET, packet_number_offset) + opened.should eq({2_u64, client_initial_payload}) + end + end + + describe "RFC 9001 Appendix A.3, server Initial" do + it "protects the server's payload into the published packet with the server's write protection" do + _, write_protection = Beryl::QUIC::PacketProtection.initial_pair_for_server(Rfc9001Appendix::DESTINATION_CONNECTION_ID) + packet = protect_packet(write_protection, Rfc9001Appendix::SERVER_INITIAL_HEADER, 1_u64, 2, Rfc9001Appendix::SERVER_INITIAL_PAYLOAD) + packet.should eq(Rfc9001Appendix::SERVER_INITIAL_PROTECTED_PACKET) + end + + it "opens the published packet with the server's keys" do + server_protection = Beryl::QUIC::PacketProtection.new(Beryl::TLS::CipherSuite::TLS_AES_128_GCM_SHA256, Rfc9001Appendix::SERVER_INITIAL_SECRET) + packet_number_offset = Rfc9001Appendix::SERVER_INITIAL_HEADER.size - 2 + opened = unprotect_packet(server_protection, Rfc9001Appendix::SERVER_INITIAL_PROTECTED_PACKET, packet_number_offset) + opened.should eq({1_u64, Rfc9001Appendix::SERVER_INITIAL_PAYLOAD}) + end + end + + describe "RFC 9001 Appendix A.5, ChaCha20-Poly1305 short header packet" do + it "derives the key, IV, header protection key and key update secret" do + hash = Beryl::TLS::HashAlgorithm::SHA256 + secret = Rfc9001Appendix::CHACHA20_SECRET + Beryl::TLS::KeySchedule.expand_label(hash, secret, "quic key", Bytes.empty, 32).should eq(Rfc9001Appendix::CHACHA20_KEY) + Beryl::TLS::KeySchedule.expand_label(hash, secret, "quic iv", Bytes.empty, 12).should eq(Rfc9001Appendix::CHACHA20_IV) + Beryl::TLS::KeySchedule.expand_label(hash, secret, "quic hp", Bytes.empty, 32).should eq(Rfc9001Appendix::CHACHA20_HP) + Beryl::TLS::KeySchedule.expand_label(hash, secret, "quic ku", Bytes.empty, 32).should eq(Rfc9001Appendix::CHACHA20_KU) + end + + it "seals with the published nonce and ciphertext" do + protection = Beryl::QUIC::PacketProtection.new(Beryl::TLS::CipherSuite::TLS_CHACHA20_POLY1305_SHA256, Rfc9001Appendix::CHACHA20_SECRET) + protection.seal(Rfc9001Appendix::CHACHA20_PACKET_NUMBER, Rfc9001Appendix::CHACHA20_HEADER, Rfc9001Appendix::CHACHA20_PLAINTEXT) + .should eq(Rfc9001Appendix::CHACHA20_CIPHERTEXT) + expected = Beryl::Crypto::V1::ChaCha20Poly1305.new(Rfc9001Appendix::CHACHA20_KEY) + .encrypt(Rfc9001Appendix::CHACHA20_PLAINTEXT, nonce: Rfc9001Appendix::CHACHA20_NONCE, associated_data: Rfc9001Appendix::CHACHA20_HEADER) + expected.should eq(Rfc9001Appendix::CHACHA20_CIPHERTEXT) + end + + it "computes the published header protection mask" do + protection = Beryl::QUIC::PacketProtection.new(Beryl::TLS::CipherSuite::TLS_CHACHA20_POLY1305_SHA256, Rfc9001Appendix::CHACHA20_SECRET) + protection.header_protection_mask(Rfc9001Appendix::CHACHA20_SAMPLE).should eq(Rfc9001Appendix::CHACHA20_MASK) + end + + it "protects the packet into the published 21 bytes and opens it again" do + protection = Beryl::QUIC::PacketProtection.new(Beryl::TLS::CipherSuite::TLS_CHACHA20_POLY1305_SHA256, Rfc9001Appendix::CHACHA20_SECRET) + # The packet number is sent on 3 bytes (49140); the nonce uses all of it. + protected_payload = protection.seal(Rfc9001Appendix::CHACHA20_PACKET_NUMBER, Rfc9001Appendix::CHACHA20_HEADER, Rfc9001Appendix::CHACHA20_PLAINTEXT) + packet = Bytes.new(Rfc9001Appendix::CHACHA20_HEADER.size + protected_payload.size) + Rfc9001Appendix::CHACHA20_HEADER.copy_to(packet) + protected_payload.copy_to(packet + Rfc9001Appendix::CHACHA20_HEADER.size) + mask = protection.header_protection_mask(packet[1 + 4, 16]) + packet[0] ^= mask[0] & 0x1f + 3.times { |index| packet[1 + index] ^= mask[1 + index] } + packet.should eq(Rfc9001Appendix::CHACHA20_PACKET) + + unprotected = packet.dup + unprotected[0] ^= mask[0] & 0x1f + 3.times { |index| unprotected[1 + index] ^= mask[1 + index] } + unprotected[0, 4].should eq(Rfc9001Appendix::CHACHA20_HEADER) + protection.open(Rfc9001Appendix::CHACHA20_PACKET_NUMBER, unprotected[0, 4], unprotected[4..]).should eq(Rfc9001Appendix::CHACHA20_PLAINTEXT) + end + end + + describe "#next_generation" do + it "moves the secret forward with quic ku and keeps the header protection key" do + suite = Beryl::TLS::CipherSuite::TLS_CHACHA20_POLY1305_SHA256 + protection = Beryl::QUIC::PacketProtection.new(suite, Rfc9001Appendix::CHACHA20_SECRET) + next_protection = protection.next_generation + updated_by_hand = Beryl::QUIC::PacketProtection.new(suite, Rfc9001Appendix::CHACHA20_KU) + header = Rfc9001Appendix::CHACHA20_HEADER + next_protection.seal(7_u64, header, "after the update".to_slice).should eq(updated_by_hand.seal(7_u64, header, "after the update".to_slice)) + next_protection.seal(7_u64, header, "after the update".to_slice).should_not eq(protection.seal(7_u64, header, "after the update".to_slice)) + # The key phase changes the packet key only (RFC 9001 §6). + next_protection.header_protection_mask(Rfc9001Appendix::CHACHA20_SAMPLE).should eq(Rfc9001Appendix::CHACHA20_MASK) + updated_by_hand.header_protection_mask(Rfc9001Appendix::CHACHA20_SAMPLE).should_not eq(Rfc9001Appendix::CHACHA20_MASK) + end + + it "keeps the shared header protection key until the last generation is wiped" do + protection = Beryl::QUIC::PacketProtection.new(Beryl::TLS::CipherSuite::TLS_AES_256_GCM_SHA384, Bytes.new(48, 7_u8)) + next_protection = protection.next_generation + mask = protection.header_protection_mask(Rfc9001Appendix::CLIENT_INITIAL_SAMPLE) + protection.wipe + expect_raises(Beryl::Crypto::KeyWiped) { protection.seal(0_u64, Bytes.empty, Bytes.empty) } + expect_raises(Beryl::Crypto::KeyWiped) { protection.header_protection_mask(Rfc9001Appendix::CLIENT_INITIAL_SAMPLE) } + next_protection.header_protection_mask(Rfc9001Appendix::CLIENT_INITIAL_SAMPLE).should eq(mask) + next_protection.wipe + expect_raises(Beryl::Crypto::KeyWiped) { next_protection.header_protection_mask(Rfc9001Appendix::CLIENT_INITIAL_SAMPLE) } + expect_raises(Beryl::Crypto::KeyWiped) { next_protection.next_generation } + end + end + + describe "#open" do + it "returns nil when any bit of the payload, the tag or the header was flipped" do + {Beryl::TLS::CipherSuite::TLS_AES_128_GCM_SHA256, Beryl::TLS::CipherSuite::TLS_AES_256_GCM_SHA384, + Beryl::TLS::CipherSuite::TLS_CHACHA20_POLY1305_SHA256}.each do |suite| + protection = Beryl::QUIC::PacketProtection.new(suite, Bytes.new(suite.hash_algorithm.bytesize, 3_u8)) + header = "c3000000010000".hexbytes + sealed = protection.seal(9_u64, header, "a short payload".to_slice) + protection.open(9_u64, header, sealed).should eq("a short payload".to_slice) + {0, sealed.size // 2, sealed.size - 1}.each do |index| + tampered = sealed.dup + tampered[index] ^= 0x01 + protection.open(9_u64, header, tampered).should be_nil + end + tampered_header = header.dup + tampered_header[0] ^= 0x01 + protection.open(9_u64, tampered_header, sealed).should be_nil + protection.open(10_u64, header, sealed).should be_nil + protection.open(9_u64, header, sealed[0, 15]).should be_nil + end + end + + it "opens and seals into caller storage" do + protection = Beryl::QUIC::PacketProtection.new(Beryl::TLS::CipherSuite::TLS_AES_128_GCM_SHA256, Rfc9001Appendix::SERVER_INITIAL_SECRET) + header = Rfc9001Appendix::SERVER_INITIAL_HEADER + storage = Bytes.new(200, 0xee_u8) + written = protection.seal(1_u64, header, Rfc9001Appendix::SERVER_INITIAL_PAYLOAD, into: storage) + written.should eq(Rfc9001Appendix::SERVER_INITIAL_PAYLOAD.size + 16) + storage[0, written].should eq(protection.seal(1_u64, header, Rfc9001Appendix::SERVER_INITIAL_PAYLOAD)) + storage[written].should eq(0xee_u8) + + plaintext_storage = Bytes.new(150) + protection.open(1_u64, header, storage[0, written], into: plaintext_storage).should eq(Rfc9001Appendix::SERVER_INITIAL_PAYLOAD.size) + plaintext_storage[0, Rfc9001Appendix::SERVER_INITIAL_PAYLOAD.size].should eq(Rfc9001Appendix::SERVER_INITIAL_PAYLOAD) + storage[3] ^= 0x80 + protection.open(1_u64, header, storage[0, written], into: plaintext_storage).should be_nil + plaintext_storage[0, Rfc9001Appendix::SERVER_INITIAL_PAYLOAD.size].all?(&.zero?).should be_true + expect_raises(Beryl::Crypto::OutputSizeMismatch) { protection.seal(1_u64, header, Bytes.new(10), into: Bytes.new(25)) } + end + end +end + +describe "Beryl::QUIC.retry_integrity_tag" do + it "computes the tag of the RFC 9001 Appendix A.4 Retry packet" do + packet = Rfc9001Appendix::RETRY_PACKET + Beryl::QUIC.retry_integrity_tag(Rfc9001Appendix::DESTINATION_CONNECTION_ID, packet[0, packet.size - 16]).should eq(packet[packet.size - 16, 16]) + end +end diff --git a/spec/beryl/quic/server_handshake_spec.cr b/spec/beryl/quic/server_handshake_spec.cr new file mode 100644 index 0000000..d17a5f7 --- /dev/null +++ b/spec/beryl/quic/server_handshake_spec.cr @@ -0,0 +1,336 @@ +require "../../spec_helper" + +private alias Level = Beryl::QUIC::EncryptionLevel +private alias Codec = Beryl::TLS::Messages::ExtensionCodec +private alias AlertDescription = Beryl::TLS::AlertDescription + +private CLIENT_TRANSPORT_PARAMETERS = "0408ffffffffffffffff05048000ffff".hexbytes +private SERVER_TRANSPORT_PARAMETERS = "0f088394c8f03e5157080e0104".hexbytes + +# A QUIC client built in the spec from Beryl's message codecs, key exchange +# and key schedule: it writes a ClientHello, reads the server's flights and +# answers with its Finished. +private class QuicSpecClient + getter cipher_suite : Beryl::TLS::CipherSuite? = nil + getter client_handshake_secret = Bytes.empty + getter server_handshake_secret = Bytes.empty + getter client_application_secret = Bytes.empty + getter server_application_secret = Bytes.empty + getter list_of_encrypted_extensions = [] of Beryl::TLS::Messages::Extension + getter? has_received_hello_retry_request = false + + property list_of_cipher_suites : Array(Beryl::TLS::CipherSuite) = [Beryl::TLS::CipherSuite::TLS_AES_128_GCM_SHA256] + property list_of_supported_groups : Array(Beryl::TLS::NamedGroup) = [Beryl::TLS::NamedGroup::X25519] + property list_of_key_share_groups : Array(Beryl::TLS::NamedGroup) = [Beryl::TLS::NamedGroup::X25519] + property list_of_alpn_protocols : Array(String)? = ["h3"] + property transport_parameters : Bytes? = CLIENT_TRANSPORT_PARAMETERS + property legacy_session_id : Bytes = Bytes.empty + property list_of_extra_extensions = [] of Beryl::TLS::Messages::Extension + + @random : Bytes = Random::Secure.random_bytes(32) + @transcript = Beryl::TLS::TranscriptHash.new + @key_exchanges = {} of Beryl::TLS::NamedGroup => Beryl::TLS::KeyExchange + @first_client_hello : Bytes? = nil + + def client_hello : Bytes + randomness = Beryl::TLS::HandshakeRandomness.new + list_of_shares = list_of_key_share_groups.map do |group| + exchange = @key_exchanges[group] ||= Beryl::TLS::KeyExchange.generate(group, randomness) + Codec::KeyShareEntry.new(group.value, exchange.public_key_bytes) + end + list_of_extensions = [ + Beryl::TLS::Messages::Extension.new(Beryl::TLS::ExtensionType::ServerName.value, Codec.encode_server_name("localhost")), + Beryl::TLS::Messages::Extension.new(Beryl::TLS::ExtensionType::SupportedGroups.value, Codec.encode_u16_list(list_of_supported_groups.map(&.value))), + Beryl::TLS::Messages::Extension.new(Beryl::TLS::ExtensionType::SignatureAlgorithms.value, + Codec.encode_u16_list([Beryl::TLS::SignatureScheme::EcdsaSecp256r1Sha256.value, Beryl::TLS::SignatureScheme::RsaPssRsaeSha256.value])), + Beryl::TLS::Messages::Extension.new(Beryl::TLS::ExtensionType::KeyShare.value, Codec.encode_client_key_shares(list_of_shares)), + Beryl::TLS::Messages::Extension.new(Beryl::TLS::ExtensionType::SupportedVersions.value, Codec.encode_client_supported_versions([Beryl::TLS::ProtocolVersion::TLS_1_3])), + ] + if protocols = list_of_alpn_protocols + list_of_extensions << Beryl::TLS::Messages::Extension.new(Beryl::TLS::ExtensionType::ApplicationLayerProtocolNegotiation.value, Codec.encode_protocol_names(protocols)) + end + if parameters = transport_parameters + list_of_extensions << Beryl::TLS::Messages::Extension.new(Beryl::TLS::ExtensionType::QuicTransportParameters.value, parameters) + end + list_of_extensions.concat(list_of_extra_extensions) + message = Beryl::TLS::Messages::ClientHello.new(@random, legacy_session_id, list_of_cipher_suites.map(&.value), list_of_extensions).encode + @first_client_hello ||= message + message + end + + # Reads the server's Initial bytes. Returns the second ClientHello when + # they hold a HelloRetryRequest, nil when they hold the ServerHello. + def receive_initial(bytes : Bytes) : Bytes? + list_of_messages = split_messages(bytes) + list_of_messages.size.should eq(1) + message = list_of_messages.first + server_hello = Beryl::TLS::Messages::ServerHello.decode(Beryl::TLS::Messages.unwrap(message)[1]) + server_hello.legacy_session_id_echo.should eq(legacy_session_id) + suite = Beryl::TLS::CipherSuite.new(server_hello.cipher_suite) + hash = suite.hash_algorithm + if server_hello.hello_retry_request? + @has_received_hello_retry_request = true + group_value = Codec.decode_selected_group(server_hello.extension(Beryl::TLS::ExtensionType::KeyShare) || raise "no key_share") + first_client_hello = @first_client_hello || raise "no first ClientHello" + @transcript.add(first_client_hello) + @transcript.replace_with_message_hash(hash) + @transcript.add(message) + self.list_of_key_share_groups = [Beryl::TLS::NamedGroup.new(group_value)] + second_client_hello = client_hello + @transcript.add(second_client_hello) + return second_client_hello + end + + @transcript.add(@first_client_hello || raise "no ClientHello") unless has_received_hello_retry_request? + @transcript.add(message) + @cipher_suite = suite + entry = Codec.decode_server_key_share(server_hello.extension(Beryl::TLS::ExtensionType::KeyShare) || raise "no key_share") + exchange = @key_exchanges[Beryl::TLS::NamedGroup.new(entry.group_value)] + schedule = Beryl::TLS::KeySchedule.new(hash) + schedule.enter_handshake_stage(exchange.shared_secret(entry.key_exchange)) + digest = @transcript.digest(hash) + @client_handshake_secret = schedule.client_handshake_traffic_secret(digest) + @server_handshake_secret = schedule.server_handshake_traffic_secret(digest) + @schedule = schedule + nil + end + + # Reads the server's Handshake flight and returns the client's Finished. + def receive_handshake(bytes : Bytes) : Bytes + suite = cipher_suite || raise "no ServerHello" + hash = suite.hash_algorithm + list_of_messages = split_messages(bytes) + list_of_messages.map { |message| Beryl::TLS::Messages.unwrap(message)[0] }.should eq([ + Beryl::TLS::HandshakeType::EncryptedExtensions, Beryl::TLS::HandshakeType::Certificate, + Beryl::TLS::HandshakeType::CertificateVerify, Beryl::TLS::HandshakeType::Finished, + ]) + @list_of_encrypted_extensions = Beryl::TLS::Messages::EncryptedExtensions.decode(Beryl::TLS::Messages.unwrap(list_of_messages[0])[1]).list_of_extensions + list_of_messages[0, 3].each { |message| @transcript.add(message) } + finished = Beryl::TLS::Messages::Finished.decode(Beryl::TLS::Messages.unwrap(list_of_messages[3])[1], hash.bytesize) + Beryl::TLS::KeySchedule.finished_matches?(hash, server_handshake_secret, @transcript.digest(hash), finished.verify_data).should be_true + @transcript.add(list_of_messages[3]) + schedule = @schedule || raise "no schedule" + schedule.enter_master_stage + digest = @transcript.digest(hash) + @client_application_secret = schedule.client_application_traffic_secret(digest) + @server_application_secret = schedule.server_application_traffic_secret(digest) + Beryl::TLS::Messages::Finished.new(Beryl::TLS::KeySchedule.finished_verify_data(hash, client_handshake_secret, digest)).encode + end + + @schedule : Beryl::TLS::KeySchedule? = nil + + private def split_messages(bytes : Bytes) : Array(Bytes) + list_of_messages = [] of Bytes + offset = 0 + while offset < bytes.size + length = (bytes[offset + 1].to_i << 16) | (bytes[offset + 2].to_i << 8) | bytes[offset + 3].to_i + list_of_messages << bytes[offset, 4 + length] + offset += 4 + length + end + list_of_messages + end +end + +private def quic_server_context : Beryl::TLS::Context::Server + context = TlsHarness.server_context + context.list_of_alpn_protocols = ["h3"] + context +end + +# Runs a whole handshake between *client* and a server on *context*, and +# returns the server's handshake and the keys it installed. +private def run_handshake(client : QuicSpecClient, context : Beryl::TLS::Context::Server = quic_server_context) : {Beryl::QUIC::ServerHandshake, Array(Beryl::QUIC::InstalledKeys)} + handshake = Beryl::QUIC::ServerHandshake.new(context, SERVER_TRANSPORT_PARAMETERS) + handshake.receive_crypto_data(Level::Initial, client.client_hello) + if second_client_hello = client.receive_initial(handshake.take_crypto_data_to_send(Level::Initial)) + handshake.take_list_of_installed_keys.should be_empty + handshake.receive_crypto_data(Level::Initial, second_client_hello) + client.receive_initial(handshake.take_crypto_data_to_send(Level::Initial)).should be_nil + end + client_finished = client.receive_handshake(handshake.take_crypto_data_to_send(Level::Handshake)) + list_of_keys = handshake.take_list_of_installed_keys + handshake.complete?.should be_false + handshake.receive_crypto_data(Level::Handshake, client_finished) + {handshake, list_of_keys} +end + +# Feeds the first ClientHello of *client* to a new handshake and returns the +# error it raised. +private def handshake_error_for(client : QuicSpecClient, context : Beryl::TLS::Context::Server = quic_server_context) : Beryl::QUIC::HandshakeError + handshake = Beryl::QUIC::ServerHandshake.new(context, SERVER_TRANSPORT_PARAMETERS) + expect_raises(Beryl::QUIC::HandshakeError) { handshake.receive_crypto_data(Level::Initial, client.client_hello) } +end + +describe Beryl::QUIC::ServerHandshake do + describe "a full handshake" do + [Beryl::TLS::CipherSuite::TLS_AES_128_GCM_SHA256, Beryl::TLS::CipherSuite::TLS_AES_256_GCM_SHA384, + Beryl::TLS::CipherSuite::TLS_CHACHA20_POLY1305_SHA256].each do |suite| + it "completes on #{suite} and installs keys that interoperate with the client's" do + client = QuicSpecClient.new + client.list_of_cipher_suites = [suite] + handshake, list_of_keys = run_handshake(client) + + handshake.complete?.should be_true + handshake.alpn_protocol.should eq("h3") + handshake.server_name.should eq("localhost") + handshake.peer_transport_parameters.should eq(CLIENT_TRANSPORT_PARAMETERS) + client.cipher_suite.should eq(suite) + client.has_received_hello_retry_request?.should be_false + client.list_of_encrypted_extensions.find { |extension| extension.type_value == 0x39 }.try(&.contents).should eq(SERVER_TRANSPORT_PARAMETERS) + client.list_of_encrypted_extensions.find { |extension| extension.type_value == 16 }.try(&.contents).should eq(Codec.encode_protocol_names(["h3"])) + handshake.take_crypto_data_to_send(Level::Initial).should be_empty + handshake.take_crypto_data_to_send(Level::Handshake).should be_empty + handshake.take_crypto_data_to_send(Level::Application).should be_empty + handshake.take_list_of_installed_keys.should be_empty + + list_of_keys.map(&.level).should eq([Level::Handshake, Level::Application]) + handshake_keys, application_keys = list_of_keys + header = "e1".hexbytes + { + {handshake_keys, client.client_handshake_secret, client.server_handshake_secret}, + {application_keys, client.client_application_secret, client.server_application_secret}, + }.each do |keys, client_secret, server_secret| + keys.write_protection.cipher_suite.should eq(suite) + client_write = Beryl::QUIC::PacketProtection.new(suite, client_secret) + client_read = Beryl::QUIC::PacketProtection.new(suite, server_secret) + client_read.open(5_u64, header, keys.write_protection.seal(5_u64, header, "from the server".to_slice)).should eq("from the server".to_slice) + keys.read_protection.open(6_u64, header, client_write.seal(6_u64, header, "from the client".to_slice)).should eq("from the client".to_slice) + end + end + end + + it "takes a ClientHello delivered one byte at a time" do + client = QuicSpecClient.new + handshake = Beryl::QUIC::ServerHandshake.new(quic_server_context, SERVER_TRANSPORT_PARAMETERS) + client_hello = client.client_hello + client_hello.each_with_index do |byte, index| + handshake.take_crypto_data_to_send(Level::Initial).should be_empty + handshake.receive_crypto_data(Level::Initial, Bytes[byte]) + handshake.take_list_of_installed_keys.should be_empty unless index == client_hello.size - 1 + end + client.receive_initial(handshake.take_crypto_data_to_send(Level::Initial)).should be_nil + client_finished = client.receive_handshake(handshake.take_crypto_data_to_send(Level::Handshake)) + handshake.take_list_of_installed_keys.size.should eq(2) + client_finished[0, 3].each { |byte| handshake.receive_crypto_data(Level::Handshake, Bytes[byte]) } + handshake.complete?.should be_false + handshake.receive_crypto_data(Level::Handshake, client_finished[3..]) + handshake.complete?.should be_true + end + + it "sends one HelloRetryRequest when the client offers no share for a group the server accepts" do + client = QuicSpecClient.new + client.list_of_supported_groups = [Beryl::TLS::NamedGroup::Secp256r1] + client.list_of_key_share_groups = [] of Beryl::TLS::NamedGroup + handshake, list_of_keys = run_handshake(client) + client.has_received_hello_retry_request?.should be_true + handshake.complete?.should be_true + list_of_keys.map(&.level).should eq([Level::Handshake, Level::Application]) + end + + it "refuses a second ClientHello that still offers no share for the group asked for" do + client = QuicSpecClient.new + client.list_of_key_share_groups = [] of Beryl::TLS::NamedGroup + handshake = Beryl::QUIC::ServerHandshake.new(quic_server_context, SERVER_TRANSPORT_PARAMETERS) + first_client_hello = client.client_hello + handshake.receive_crypto_data(Level::Initial, first_client_hello) + handshake.take_crypto_data_to_send(Level::Initial).should_not be_empty + error = expect_raises(Beryl::QUIC::HandshakeError) { handshake.receive_crypto_data(Level::Initial, first_client_hello) } + error.alert_description.should eq(AlertDescription::IllegalParameter) + end + end + + describe "the QUIC rules of RFC 9001 §8" do + it "refuses a client that offers no ALPN protocol with no_application_protocol (0x0178)" do + client = QuicSpecClient.new + client.list_of_alpn_protocols = nil + error = handshake_error_for(client) + error.alert_description.should eq(AlertDescription::NoApplicationProtocol) + error.transport_error_code.should eq(0x0178_u64) + end + + it "refuses a client whose ALPN protocols the server does not speak" do + client = QuicSpecClient.new + client.list_of_alpn_protocols = ["h2"] + handshake_error_for(client).transport_error_code.should eq(0x0178_u64) + end + + it "refuses a ClientHello without quic_transport_parameters with missing_extension (0x016d)" do + client = QuicSpecClient.new + client.transport_parameters = nil + error = handshake_error_for(client) + error.alert_description.should eq(AlertDescription::MissingExtension) + error.transport_error_code.should eq(0x016d_u64) + end + + it "treats a non-empty legacy_session_id as a PROTOCOL_VIOLATION (§8.4)" do + client = QuicSpecClient.new + client.legacy_session_id = Bytes.new(32, 1_u8) + handshake_error_for(client).transport_error_code.should eq(Beryl::QUIC::HandshakeError::PROTOCOL_VIOLATION) + end + + it "refuses an extension that appears twice, as the TLS server does" do + client = QuicSpecClient.new + client.list_of_extra_extensions = [Beryl::TLS::Messages::Extension.new(Beryl::TLS::ExtensionType::QuicTransportParameters.value, Bytes[1, 2])] + handshake_error_for(client).alert_description.should eq(AlertDescription::IllegalParameter) + end + + it "accepts no early data: early_data in the ClientHello gets no answer" do + client = QuicSpecClient.new + client.list_of_extra_extensions = [Beryl::TLS::Messages::Extension.new(Beryl::TLS::ExtensionType::EarlyData.value, Bytes.empty)] + handshake, _ = run_handshake(client) + handshake.complete?.should be_true + client.list_of_encrypted_extensions.any? { |extension| extension.type_value == Beryl::TLS::ExtensionType::EarlyData.value }.should be_false + end + + it "treats a TLS KeyUpdate message as a connection error with unexpected_message (§6)" do + handshake, _ = run_handshake(QuicSpecClient.new) + key_update = Beryl::TLS::Messages::KeyUpdate.new(Beryl::TLS::KeyUpdateRequest::UpdateNotRequested).encode + error = expect_raises(Beryl::QUIC::HandshakeError) { handshake.receive_crypto_data(Level::Application, key_update) } + error.alert_description.should eq(AlertDescription::UnexpectedMessage) + error.transport_error_code.should eq(0x010a_u64) + end + end + + describe "failures" do + it "refuses a client Finished that does not verify, and stays failed" do + client = QuicSpecClient.new + handshake = Beryl::QUIC::ServerHandshake.new(quic_server_context, SERVER_TRANSPORT_PARAMETERS) + handshake.receive_crypto_data(Level::Initial, client.client_hello) + client.receive_initial(handshake.take_crypto_data_to_send(Level::Initial)) + client_finished = client.receive_handshake(handshake.take_crypto_data_to_send(Level::Handshake)) + client_finished[-1] ^= 0x01 + error = expect_raises(Beryl::QUIC::HandshakeError) { handshake.receive_crypto_data(Level::Handshake, client_finished) } + error.alert_description.should eq(AlertDescription::DecryptError) + handshake.complete?.should be_false + expect_raises(Beryl::QUIC::HandshakeError) { handshake.receive_crypto_data(Level::Handshake, Bytes[0]) } + end + + it "refuses a declared message length over the limit before its body arrives" do + handshake = Beryl::QUIC::ServerHandshake.new(quic_server_context, SERVER_TRANSPORT_PARAMETERS) + error = expect_raises(Beryl::QUIC::HandshakeError) { handshake.receive_crypto_data(Level::Initial, Bytes[1, 0x01, 0x00, 0x01]) } + error.alert_description.should eq(AlertDescription::IllegalParameter) + end + + it "treats Initial data left unread when the Handshake keys arrive as a PROTOCOL_VIOLATION (§4.1.3)" do + client_hello = QuicSpecClient.new.client_hello + handshake = Beryl::QUIC::ServerHandshake.new(quic_server_context, SERVER_TRANSPORT_PARAMETERS) + trailing = Bytes.new(client_hello.size + 2) + client_hello.copy_to(trailing) + trailing[client_hello.size] = 20_u8 + error = expect_raises(Beryl::QUIC::HandshakeError) { handshake.receive_crypto_data(Level::Initial, trailing) } + error.transport_error_code.should eq(Beryl::QUIC::HandshakeError::PROTOCOL_VIOLATION) + end + + it "refuses handshake data at a level the handshake is not reading" do + handshake = Beryl::QUIC::ServerHandshake.new(quic_server_context, SERVER_TRANSPORT_PARAMETERS) + error = expect_raises(Beryl::QUIC::HandshakeError) { handshake.receive_crypto_data(Level::Handshake, QuicSpecClient.new.client_hello) } + error.alert_description.should eq(AlertDescription::UnexpectedMessage) + end + + it "refuses a context that asks for client certificates" do + context = quic_server_context + context.client_verify_mode = Beryl::TLS::ClientVerifyMode::Optional + expect_raises(ArgumentError) { Beryl::QUIC::ServerHandshake.new(context, SERVER_TRANSPORT_PARAMETERS) } + end + end +end diff --git a/src/beryl.cr b/src/beryl.cr index fcd8a5d..20bf3d4 100644 --- a/src/beryl.cr +++ b/src/beryl.cr @@ -5,6 +5,7 @@ require "./beryl/crypto" require "./beryl/encoding" require "./beryl/certificates" require "./beryl/tls" +require "./beryl/quic" # Security for Amber V2. # diff --git a/src/beryl/quic.cr b/src/beryl/quic.cr new file mode 100644 index 0000000..b6ea6ed --- /dev/null +++ b/src/beryl/quic.cr @@ -0,0 +1,19 @@ +require "./tls" +require "./quic/encryption_level" +require "./quic/handshake_error" +require "./quic/header_protection_key" +require "./quic/packet_protection" +require "./quic/retry_integrity_tag" +require "./quic/installed_keys" +require "./quic/server_handshake" + +# The cryptographic half of QUIC version 1 (RFC 9001): the initial secrets, +# packet and header protection, key update, and a TLS 1.3 server handshake +# that carries its messages as CRYPTO data instead of records. +# +# Everything here is sans-IO. A QUIC transport (such as Mica's) frames the +# bytes `ServerHandshake` produces into CRYPTO frames, hands it the client's +# CRYPTO bytes in order, and seals and opens packets with the +# `PacketProtection` objects it installs. Keys never leave Beryl as bytes. +module Beryl::QUIC +end diff --git a/src/beryl/quic/encryption_level.cr b/src/beryl/quic/encryption_level.cr new file mode 100644 index 0000000..a89142e --- /dev/null +++ b/src/beryl/quic/encryption_level.cr @@ -0,0 +1,9 @@ +module Beryl::QUIC + # The encryption levels a QUIC handshake carries CRYPTO data at + # (RFC 9001 §4.1.4). 0-RTT carries none, so it has no level here. + enum EncryptionLevel + Initial + Handshake + Application + end +end diff --git a/src/beryl/quic/handshake_error.cr b/src/beryl/quic/handshake_error.cr new file mode 100644 index 0000000..72efba8 --- /dev/null +++ b/src/beryl/quic/handshake_error.cr @@ -0,0 +1,23 @@ +require "../tls/error" + +module Beryl::QUIC + # A QUIC handshake failed. `alert_description` is the TLS alert, and + # `transport_error_code` the QUIC error the transport closes the + # connection with: CRYPTO_ERROR, `0x0100` plus the alert (RFC 9001 §4.8), + # for everything but the few failures RFC 9001 makes a + # PROTOCOL_VIOLATION (§4.1.3, §8.4). + class HandshakeError < TLS::Error + # The QUIC transport error code PROTOCOL_VIOLATION (RFC 9000 §20.1). + PROTOCOL_VIOLATION = 0x0a_u64 + # The first CRYPTO_ERROR code; the alert is added to it (RFC 9001 §4.8). + CRYPTO_ERROR_BASE = 0x0100_u64 + + getter transport_error_code : UInt64 + + def initialize(message : String, alert_description : TLS::AlertDescription = TLS::AlertDescription::InternalError, + transport_error_code : UInt64? = nil) + super(message, alert_description) + @transport_error_code = transport_error_code || CRYPTO_ERROR_BASE + alert_description.value + end + end +end diff --git a/src/beryl/quic/header_protection_key.cr b/src/beryl/quic/header_protection_key.cr new file mode 100644 index 0000000..9832bd5 --- /dev/null +++ b/src/beryl/quic/header_protection_key.cr @@ -0,0 +1,108 @@ +require "../crypto" +require "../tls/protocol" +require "../tls/key_schedule" + +module Beryl::QUIC + # :nodoc: + # + # The header protection key of one direction (RFC 9001 §5.4): it turns a + # 16-byte sample of a packet's ciphertext into the 5-byte mask over the + # packet's first byte and packet number. A key update keeps this key + # (§6), so every generation of a `PacketProtection` shares one instance; + # it is wiped when the last generation holding it is wiped. + class HeaderProtectionKey + SAMPLE_BYTESIZE = 16 + MASK_BYTESIZE = 5 + + @cipher_suite : TLS::CipherSuite + # The ChaCha20 key; empty for an AES suite. + @chacha20_key : Bytes + @round_count : Int32 + # The AES round keys for the processor's instructions, or as the + # portable code's words; whichever is unused is empty. + @round_key_bytes : Bytes + @round_keys : Slice(UInt64) + @generation_count = 1 + + def initialize(@cipher_suite : TLS::CipherSuite, traffic_secret : Bytes) + key = TLS::KeySchedule.expand_label(@cipher_suite.hash_algorithm, traffic_secret, "quic hp", Bytes.empty, @cipher_suite.key_bytesize) + @round_key_bytes = Bytes.empty + @round_keys = Slice(UInt64).empty + if @cipher_suite.tls_chacha20_poly1305_sha256? + @chacha20_key = key + @round_count = 0 + return + end + + @chacha20_key = Bytes.empty + @round_count = Crypto::V1::BitslicedAdvancedEncryptionStandard.round_count_for(key.size) + if Crypto::ProcessorFeatures::HAS_GALOIS_COUNTER_MODE_INSTRUCTIONS + @round_key_bytes = Bytes.new(Crypto::V1::BitslicedAdvancedEncryptionStandard::ROUND_KEY_BYTESIZE) + Crypto::DataIndependentTiming.run { Crypto::V1::BitslicedAdvancedEncryptionStandard.write_round_key_bytes(key, @round_key_bytes) } + else + @round_keys = Slice(UInt64).new(Crypto::V1::BitslicedAdvancedEncryptionStandard::ROUND_KEY_WORD_COUNT, 0_u64) + Crypto::DataIndependentTiming.run { Crypto::V1::BitslicedAdvancedEncryptionStandard.expand_key(key, @round_keys) } + end + Crypto::SecretWiping.wipe(key) + end + + # Returns the 5-byte mask for *sample*: the first bytes of AES-ECB of + # the sample (§5.4.3), or of ChaCha20 keyed with this key, its block + # counter the sample's first four bytes (little-endian) and its nonce + # the other twelve, over five zero bytes (§5.4.4). + def mask(sample : Bytes) : Bytes + raise Crypto::KeyWiped.new("the header protection key was wiped") if @generation_count == 0 + unless sample.size == SAMPLE_BYTESIZE + raise ArgumentError.new("a header protection sample is #{SAMPLE_BYTESIZE} bytes, not #{sample.size}") + end + mask = Bytes.new(MASK_BYTESIZE) + Crypto::DataIndependentTiming.run do + if @cipher_suite.tls_chacha20_poly1305_sha256? + counter = IO::ByteFormat::LittleEndian.decode(UInt32, sample[0, 4]) + Crypto::V1::ChaCha20StreamCipher.xor_keystream(@chacha20_key, sample[4, 12], counter, mask, mask) + else + write_aes_mask(sample, mask) + end + end + mask + end + + # Notes one more `PacketProtection` generation holding this key. + def share : HeaderProtectionKey + raise Crypto::KeyWiped.new("the header protection key was wiped") if @generation_count == 0 + @generation_count += 1 + self + end + + # Notes that one generation let go of this key, and wipes the key when + # it was the last. + def release : Nil + return if @generation_count == 0 + @generation_count -= 1 + return unless @generation_count == 0 + Crypto::SecretWiping.wipe(@chacha20_key) + Crypto::SecretWiping.wipe(@round_key_bytes) + Crypto::SecretWiping.wipe(@round_keys) + end + + # AES of one block is the first block of counter mode's keystream when + # the counter block is that block, so the counter-mode code both + # implementations already have encrypts the sample; XORed into zeros, + # the keystream is the encryption itself. + private def write_aes_mask(sample : Bytes, mask : Bytes) : Nil + encrypted_storage = StaticArray(UInt8, 16).new(0_u8) + encrypted = encrypted_storage.to_slice + counter_storage = StaticArray(UInt8, 16).new(0_u8) + counter_block = counter_storage.to_slice + sample.copy_to(counter_block) + if Crypto::ProcessorFeatures::HAS_GALOIS_COUNTER_MODE_INSTRUCTIONS + Crypto::V1::GaloisCounterModeWithProcessorInstructions.xor_counter_keystream(@round_key_bytes, @round_count, counter_block, encrypted, encrypted) + else + Crypto::V1::BitslicedAdvancedEncryptionStandard.xor_counter_keystream(@round_keys, @round_count, counter_block, encrypted, encrypted) + end + encrypted[0, MASK_BYTESIZE].copy_to(mask) + Crypto::SecretWiping.wipe(encrypted) + Crypto::SecretWiping.wipe(counter_block) + end + end +end diff --git a/src/beryl/quic/installed_keys.cr b/src/beryl/quic/installed_keys.cr new file mode 100644 index 0000000..b2520f6 --- /dev/null +++ b/src/beryl/quic/installed_keys.cr @@ -0,0 +1,10 @@ +require "./encryption_level" +require "./packet_protection" + +module Beryl::QUIC + # The packet protection of one encryption level, both directions, as + # `ServerHandshake#take_list_of_installed_keys` hands it to the transport. + # The transport owns both objects from then on and wipes them when it + # discards the level. + record InstalledKeys, level : EncryptionLevel, read_protection : PacketProtection, write_protection : PacketProtection +end diff --git a/src/beryl/quic/packet_protection.cr b/src/beryl/quic/packet_protection.cr new file mode 100644 index 0000000..b54b39a --- /dev/null +++ b/src/beryl/quic/packet_protection.cr @@ -0,0 +1,186 @@ +require "../crypto" +require "../tls/protocol" +require "../tls/key_schedule" +require "./header_protection_key" + +module Beryl::QUIC + # One direction of one encryption level's packet protection (RFC 9001 + # §5): the AEAD keyed from a traffic secret with the labels `quic key` + # and `quic iv`, and the header protection key from `quic hp`. + # + # ``` + # read_protection, write_protection = Beryl::QUIC::PacketProtection.initial_pair_for_server(destination_connection_id) + # protected_payload = write_protection.seal(packet_number, header, payload) + # mask = write_protection.header_protection_mask(sample) # 16 bytes of the protected packet, RFC 9001 §5.4.2 + # ``` + # + # The caller supplies the packet number, so one instance seals and opens + # packets in any order; a packet number must never be sealed twice. + # A traffic secret passed in is copied, and stays the caller's to wipe. + class PacketProtection + # The QUIC version 1 initial salt (RFC 9001 §5.2). + INITIAL_SALT = Bytes[ + 0x38, 0x76, 0x2c, 0xf7, 0xf5, 0x59, 0x34, 0xb3, 0x4d, 0x17, + 0x9a, 0xe6, 0xa4, 0xc8, 0x0c, 0xad, 0xcc, 0xbb, 0x7f, 0x0a, + ] + # The largest packet number (RFC 9000 §12.3). + LARGEST_PACKET_NUMBER = (1_u64 << 62) - 1 + + getter cipher_suite : TLS::CipherSuite + + @authenticated_encryption : Crypto::V1::AuthenticatedEncryption + @iv : Bytes + @traffic_secret : Bytes + @header_protection_key : HeaderProtectionKey + # The nonce of the packet being sealed or opened, wiped after each. + @nonce = Bytes.new(TLS::KeySchedule::IV_BYTESIZE) + @is_wiped = false + + # Returns the server's Initial protection for a connection whose client + # sent *client_destination_connection_id* as its Destination Connection + # ID (the original one, or the one a Retry gave it): `{read, write}`, read + # under the client's initial secret and write under the server's + # (§5.2). Initial packets always use AES-128-GCM. + def self.initial_pair_for_server(client_destination_connection_id : Bytes) : {PacketProtection, PacketProtection} + hash = TLS::HashAlgorithm::SHA256 + initial_secret = hash.extract(client_destination_connection_id, salt: INITIAL_SALT) + client_initial_secret = TLS::KeySchedule.expand_label(hash, initial_secret, "client in", Bytes.empty, hash.bytesize) + server_initial_secret = TLS::KeySchedule.expand_label(hash, initial_secret, "server in", Bytes.empty, hash.bytesize) + suite = TLS::CipherSuite::TLS_AES_128_GCM_SHA256 + {new(suite, client_initial_secret), new(suite, server_initial_secret)} + ensure + initial_secret.try { |secret| Crypto::SecretWiping.wipe(secret) } + client_initial_secret.try { |secret| Crypto::SecretWiping.wipe(secret) } + server_initial_secret.try { |secret| Crypto::SecretWiping.wipe(secret) } + end + + def initialize(@cipher_suite : TLS::CipherSuite, traffic_secret : Bytes) + @authenticated_encryption, @iv = PacketProtection.derive_packet_key(@cipher_suite, traffic_secret) + @traffic_secret = traffic_secret.dup + @header_protection_key = HeaderProtectionKey.new(@cipher_suite, traffic_secret) + end + + # :nodoc: + # + # A later generation (`next_generation`), which shares + # *header_protection_key* with the ones before it. + def initialize(@cipher_suite : TLS::CipherSuite, traffic_secret : Bytes, @header_protection_key : HeaderProtectionKey) + @authenticated_encryption, @iv = PacketProtection.derive_packet_key(@cipher_suite, traffic_secret) + @traffic_secret = traffic_secret.dup + end + + # The tag size of every QUIC version 1 AEAD. + def tag_bytesize : Int32 + 16 + end + + # Returns the protected payload: *plaintext* encrypted and followed by + # the tag, with *header* (the unprotected header, packet number + # included) as associated data and the IV XORed with the packet number + # as nonce (§5.3). + def seal(packet_number : UInt64, header : Bytes, plaintext : Bytes) : Bytes + ciphertext_and_tag = Bytes.new(plaintext.size + tag_bytesize) + seal(packet_number, header, plaintext, into: ciphertext_and_tag) + ciphertext_and_tag + end + + # Seals as `seal` does, writing the ciphertext and tag into the front of + # *ciphertext_and_tag_storage*, which holds at least `tag_bytesize` + # bytes more than *plaintext* and does not overlap it. Returns the + # number of bytes written. + def seal(packet_number : UInt64, header : Bytes, plaintext : Bytes, *, into ciphertext_and_tag_storage : Bytes) : Int32 + sealed_bytesize = plaintext.size + tag_bytesize + if ciphertext_and_tag_storage.size < sealed_bytesize + raise Crypto::OutputSizeMismatch.new("the protected payload is #{sealed_bytesize} bytes, the buffer holds #{ciphertext_and_tag_storage.size}") + end + @authenticated_encryption.encrypt(plaintext, into: ciphertext_and_tag_storage[0, sealed_bytesize], + nonce: nonce_for(packet_number), associated_data: header) + sealed_bytesize + ensure + Crypto::SecretWiping.wipe(@nonce) + end + + # Returns the plaintext of a protected payload, or nil when it fails + # authentication (§5.3); the transport drops such a packet. + def open(packet_number : UInt64, header : Bytes, ciphertext_and_tag : Bytes) : Bytes? + return nil if ciphertext_and_tag.size < tag_bytesize + plaintext = Bytes.new(ciphertext_and_tag.size - tag_bytesize) + return nil unless open(packet_number, header, ciphertext_and_tag, into: plaintext) + plaintext + end + + # Opens as `open` does, decrypting into the front of *plaintext_storage*, + # which holds at least `tag_bytesize` bytes fewer than + # *ciphertext_and_tag* and does not overlap it. Returns the plaintext's + # size, or nil (with the front of the storage zeroed) when the payload + # fails authentication. + def open(packet_number : UInt64, header : Bytes, ciphertext_and_tag : Bytes, *, into plaintext_storage : Bytes) : Int32? + return nil if ciphertext_and_tag.size < tag_bytesize + plaintext_bytesize = ciphertext_and_tag.size - tag_bytesize + if plaintext_storage.size < plaintext_bytesize + raise Crypto::OutputSizeMismatch.new("the plaintext is #{plaintext_bytesize} bytes, the buffer holds #{plaintext_storage.size}") + end + is_authentic = @authenticated_encryption.decrypt(ciphertext_and_tag, into: plaintext_storage[0, plaintext_bytesize], + nonce: nonce_for(packet_number), associated_data: header) + is_authentic ? plaintext_bytesize : nil + ensure + Crypto::SecretWiping.wipe(@nonce) + end + + # Returns the 5-byte header protection mask for the 16-byte *sample* of + # a packet's protected payload (§5.4). Both directions use it: the + # writer to apply the mask, the reader to remove it. + def header_protection_mask(sample : Bytes) : Bytes + raise Crypto::KeyWiped.new("this packet protection was wiped") if @is_wiped + @header_protection_key.mask(sample) + end + + # Returns the next key phase's protection (§6.1): the traffic secret + # moved forward with the label `quic ku`, and the same header + # protection key. This generation stays usable until it is wiped. + def next_generation : PacketProtection + raise Crypto::KeyWiped.new("this packet protection was wiped") if @is_wiped + hash = @cipher_suite.hash_algorithm + next_traffic_secret = TLS::KeySchedule.expand_label(hash, @traffic_secret, "quic ku", Bytes.empty, hash.bytesize) + PacketProtection.new(@cipher_suite, next_traffic_secret, @header_protection_key.share) + ensure + next_traffic_secret.try { |secret| Crypto::SecretWiping.wipe(secret) } + end + + # Wipes this generation's packet key, IV and traffic secret, and the + # header protection key once no other generation holds it. Afterward + # every method but `wipe` and `tag_bytesize` raises `Crypto::KeyWiped`. + def wipe : Nil + return if @is_wiped + @is_wiped = true + @authenticated_encryption.wipe + Crypto::SecretWiping.wipe(@iv) + Crypto::SecretWiping.wipe(@traffic_secret) + @header_protection_key.release + end + + # :nodoc: + # + # Returns the AEAD and the IV of *traffic_secret* (§5.1). + def self.derive_packet_key(cipher_suite : TLS::CipherSuite, traffic_secret : Bytes) : {Crypto::V1::AuthenticatedEncryption, Bytes} + hash = cipher_suite.hash_algorithm + key = TLS::KeySchedule.expand_label(hash, traffic_secret, "quic key", Bytes.empty, cipher_suite.key_bytesize) + iv = TLS::KeySchedule.expand_label(hash, traffic_secret, "quic iv", Bytes.empty, TLS::KeySchedule::IV_BYTESIZE) + {cipher_suite.build_authenticated_encryption(key), iv} + ensure + key.try { |bytes| Crypto::SecretWiping.wipe(bytes) } + end + + # The IV with the packet number, as 64 big-endian bits, XORed into its + # last 8 bytes (§5.3). + private def nonce_for(packet_number : UInt64) : Bytes + raise Crypto::KeyWiped.new("this packet protection was wiped") if @is_wiped + raise ArgumentError.new("the packet number #{packet_number} is past 2^62 - 1") if packet_number > LARGEST_PACKET_NUMBER + @iv.copy_to(@nonce) + 8.times do |index| + @nonce[TLS::KeySchedule::IV_BYTESIZE - 1 - index] ^= ((packet_number >> (8 * index)) & 0xFF).to_u8 + end + @nonce + end + end +end diff --git a/src/beryl/quic/retry_integrity_tag.cr b/src/beryl/quic/retry_integrity_tag.cr new file mode 100644 index 0000000..c64348c --- /dev/null +++ b/src/beryl/quic/retry_integrity_tag.cr @@ -0,0 +1,26 @@ +require "../crypto" + +module Beryl::QUIC + # The QUIC version 1 Retry integrity key and nonce (RFC 9001 §5.8). They + # are published, so the tag proves only that the Retry was not corrupted + # and that its sender saw the client's Initial. + private RETRY_INTEGRITY_KEY = Bytes[0xbe, 0x0c, 0x69, 0x0b, 0x9f, 0x66, 0x57, 0x5a, 0x1d, 0x76, 0x6b, 0x54, 0xe3, 0x68, 0xc8, 0x4e] + private RETRY_INTEGRITY_NONCE = Bytes[0x46, 0x15, 0x99, 0xd3, 0x5d, 0x63, 0x2b, 0xf2, 0x23, 0x98, 0x25, 0xbb] + + # Returns the 16-byte Retry Integrity Tag (RFC 9001 §5.8) of a Retry + # packet answering a client whose Initial carried + # *original_destination_connection_id*: AES-128-GCM under the fixed key + # and nonce over nothing, with the Retry Pseudo-Packet (the ODCID with + # its one-byte length, then *retry_packet_without_tag*) as associated + # data. A server appends it to the packet; a client compares it. + def self.retry_integrity_tag(original_destination_connection_id : Bytes, retry_packet_without_tag : Bytes) : Bytes + if original_destination_connection_id.size > 255 + raise ArgumentError.new("a connection ID of #{original_destination_connection_id.size} bytes") + end + pseudo_packet = Bytes.new(1 + original_destination_connection_id.size + retry_packet_without_tag.size) + pseudo_packet[0] = original_destination_connection_id.size.to_u8 + original_destination_connection_id.copy_to(pseudo_packet + 1) + retry_packet_without_tag.copy_to(pseudo_packet + (1 + original_destination_connection_id.size)) + Crypto::V1::AESGCM.new(RETRY_INTEGRITY_KEY).encrypt(Bytes.empty, nonce: RETRY_INTEGRITY_NONCE, associated_data: pseudo_packet) + end +end diff --git a/src/beryl/quic/server_handshake.cr b/src/beryl/quic/server_handshake.cr new file mode 100644 index 0000000..cc7eeb8 --- /dev/null +++ b/src/beryl/quic/server_handshake.cr @@ -0,0 +1,381 @@ +require "../tls" +require "./encryption_level" +require "./handshake_error" +require "./packet_protection" +require "./installed_keys" + +module Beryl::QUIC + # The server side of the TLS 1.3 handshake QUIC runs (RFC 9001 §4), + # sans-IO: CRYPTO bytes go in per encryption level, and CRYPTO bytes to + # send and the packet protection of each new level come out. One + # instance runs one handshake. + # + # ``` + # handshake = Beryl::QUIC::ServerHandshake.new(context, local_transport_parameters) + # handshake.receive_crypto_data(Beryl::QUIC::EncryptionLevel::Initial, client_crypto_bytes) + # handshake.take_crypto_data_to_send(Beryl::QUIC::EncryptionLevel::Initial) # the ServerHello + # handshake.take_list_of_installed_keys # Handshake, then Application + # handshake.take_crypto_data_to_send(Beryl::QUIC::EncryptionLevel::Handshake) # EncryptedExtensions to Finished + # ``` + # + # It makes the same choices as `TLS::ServerHandshake` from the same + # context (both use `TLS::NegotiateParametersFromClientHello`): cipher + # suite, key exchange group with at most one HelloRetryRequest, + # certificate by server name, ALPN. On top it enforces what RFC 9001 §8 + # asks of a server: an ALPN protocol must be agreed, the client must send + # `quic_transport_parameters`, and `legacy_session_id` must be empty. It + # authenticates with a certificate on every handshake: it resumes no + # session, accepts no 0-RTT data (it never echoes early_data) and issues + # no session tickets. QUIC has no record layer, so there is no + # change_cipher_spec, record_size_limit or KeyUpdate message. + # + # Any failure raises `HandshakeError`; the handshake is over then, and + # every later call to `receive_crypto_data` raises again. + class ServerHandshake + alias ExtensionCodec = TLS::Messages::ExtensionCodec + alias Selection = TLS::NegotiateParametersFromClientHello::Selection + + # Where the handshake stands; each stage reads CRYPTO data at one level. + private enum Stage + ReadingClientHello + ReadingSecondClientHello + ReadingClientFinished + Complete + Failed + end + + # The transport parameters the client sent, unparsed (RFC 9001 §8.2): + # set once its ClientHello was read. They are authenticated only when + # the handshake completes. + getter peer_transport_parameters : Bytes? = nil + # The agreed ALPN protocol, set once the ClientHello was read. + getter alpn_protocol : String? = nil + # The server name the client asked for, if any. + getter server_name : String? = nil + + @stage = Stage::ReadingClientHello + @transcript = TLS::TranscriptHash.new + @secrets = TLS::HandshakeSecrets.new + @list_of_received_bytes_by_level : Array(IO::Memory) = Array.new(EncryptionLevel.values.size) { IO::Memory.new } + @list_of_bytes_to_send_by_level : Array(IO::Memory) = Array.new(EncryptionLevel.values.size) { IO::Memory.new } + @list_of_installed_keys = [] of InstalledKeys + @first_client_hello : TLS::Messages::ClientHello? = nil + @first_selection : Selection? = nil + @cipher_suite : TLS::CipherSuite? = nil + @client_handshake_traffic_secret : Bytes? = nil + + # Starts a handshake that answers with *context*'s certificates, + # groups, suites and ALPN protocols, and sends + # *local_transport_parameters* (the encoded QUIC transport parameters, + # RFC 9000 §18) in its EncryptedExtensions. Raises `ArgumentError` when + # *context* asks for client certificates, which this handshake does + # not request. + def initialize(@context : TLS::Context::Server, @local_transport_parameters : Bytes) + if @context.client_verify_mode.requests_certificate? + raise ArgumentError.new("the QUIC server handshake does not request client certificates") + end + @randomness = @context.randomness + @negotiation = TLS::NegotiateParametersFromClientHello.new(@context) + end + + # Takes the next contiguous CRYPTO bytes the client sent at *level*, in + # order and in chunks of any size, and runs the handshake as far as + # they allow. Raises `HandshakeError` when the handshake fails. + def receive_crypto_data(level : EncryptionLevel, data : Bytes) : Nil + if @stage.failed? + raise HandshakeError.new("the handshake already failed", TLS::AlertDescription::InternalError) + end + received_bytes = @list_of_received_bytes_by_level[level.value] + received_bytes.write(data) + while message = take_whole_message(level) + handle_message(level, message) + end + rescue error : HandshakeError + end_in_failure + raise error + rescue error : TLS::Error + end_in_failure + raise HandshakeError.new(error.message || "the handshake failed", error.alert_description) + rescue error : Crypto::Error | Certificates::Error + end_in_failure + raise HandshakeError.new(error.message || "the handshake failed", TLS::AlertDescription::InternalError) + end + + # Returns the handshake bytes produced at *level* since the last call, + # for the transport to send in CRYPTO frames; empty when there are + # none. + def take_crypto_data_to_send(level : EncryptionLevel) : Bytes + bytes_to_send = @list_of_bytes_to_send_by_level[level.value] + return Bytes.empty if bytes_to_send.size == 0 + bytes = bytes_to_send.to_slice.dup + @list_of_bytes_to_send_by_level[level.value] = IO::Memory.new + bytes + end + + # Returns the packet protection installed since the last call, in the + # order it became available: Handshake, then Application. The + # Application keys come once the server's Finished is written; their + # write side is usable at once, and their read side once `complete?`. + def take_list_of_installed_keys : Array(InstalledKeys) + list_of_keys = @list_of_installed_keys + @list_of_installed_keys = [] of InstalledKeys + list_of_keys + end + + # Returns whether the client's Finished arrived and verified. + def complete? : Bool + @stage.complete? + end + + # Wipes every secret the handshake still holds. A transport that gives + # up on a handshake before it completes or fails calls this; a + # completed or failed handshake has already wiped them. Packet + # protection already taken belongs to the transport. + def wipe : Nil + @client_handshake_traffic_secret = nil + @secrets.wipe + end + + private def end_in_failure : Nil + @stage = Stage::Failed + wipe + @list_of_installed_keys.each do |keys| + keys.read_protection.wipe + keys.write_protection.wipe + end + @list_of_installed_keys.clear + end + + # Takes one whole handshake message from what arrived at *level*, or + # returns nil while it is incomplete. A declared length over the + # context's largest handshake message is refused before its body + # arrives, so a level never buffers more than one largest message. + private def take_whole_message(level : EncryptionLevel) : Bytes? + received_bytes = @list_of_received_bytes_by_level[level.value] + buffered = received_bytes.to_slice + return nil if buffered.size < 4 + declared_bytesize = (buffered[1].to_i << 16) | (buffered[2].to_i << 8) | buffered[3].to_i + if declared_bytesize > @context.limits.largest_handshake_message_bytesize + raise HandshakeError.new("a handshake message of #{declared_bytesize} bytes", TLS::AlertDescription::IllegalParameter) + end + message_bytesize = 4 + declared_bytesize + return nil if buffered.size < message_bytesize + message = buffered[0, message_bytesize].dup + remaining_bytes = IO::Memory.new + remaining_bytes.write(buffered[message_bytesize..]) + @list_of_received_bytes_by_level[level.value] = remaining_bytes + message + end + + private def handle_message(level : EncryptionLevel, message : Bytes) : Nil + # QUIC updates keys with the key phase bit instead (RFC 9001 §6). + if TLS::Messages.unwrap(message)[0] == TLS::HandshakeType::KeyUpdate + raise HandshakeError.new("a KeyUpdate message, which QUIC does not use", TLS::AlertDescription::UnexpectedMessage) + end + case @stage + when Stage::ReadingClientHello + expect_level(level, EncryptionLevel::Initial) + handle_first_client_hello(message) + when Stage::ReadingSecondClientHello + expect_level(level, EncryptionLevel::Initial) + handle_second_client_hello(message) + when Stage::ReadingClientFinished + expect_level(level, EncryptionLevel::Handshake) + handle_client_finished(message) + else + raise HandshakeError.new("a handshake message at #{level} after the handshake completed", TLS::AlertDescription::UnexpectedMessage) + end + end + + private def expect_level(level : EncryptionLevel, expected_level : EncryptionLevel) : Nil + return if level == expected_level + raise HandshakeError.new("handshake data at #{level} where #{expected_level} was expected", TLS::AlertDescription::UnexpectedMessage) + end + + private def handle_first_client_hello(message : Bytes) : Nil + client_hello = decode_client_hello(message) + selection = @negotiation.select_parameters(client_hello, nil) + accept_quic_selection(selection) + # The certificate for the name the client asked for; a name the + # server does not serve is refused before any reply. + @context.certified_key_for_server_name(selection.server_name) + + if selection.client_key_share + answer_client_hello(client_hello, message, selection) + return + end + + # No share for the group the server wants: one HelloRetryRequest + # (RFC 9846 §4.1.4). The client waits for it, so nothing may follow + # the first ClientHello. + ensure_level_is_consumed(EncryptionLevel::Initial, "data after the first ClientHello", TLS::AlertDescription::UnexpectedMessage, nil) + @transcript.add(message) + @transcript.replace_with_message_hash(selection.cipher_suite.hash_algorithm) + hello_retry_request = TLS::Messages::ServerHello.new(TLS::Messages::HELLO_RETRY_REQUEST_RANDOM, client_hello.legacy_session_id, + selection.cipher_suite.value, [ + TLS::Messages::Extension.new(TLS::ExtensionType::KeyShare.value, ExtensionCodec.encode_selected_group(selection.group.value)), + TLS::Messages::Extension.new(TLS::ExtensionType::SupportedVersions.value, ExtensionCodec.encode_selected_version(TLS::ProtocolVersion::TLS_1_3)), + ]).encode + write_and_record(EncryptionLevel::Initial, hello_retry_request) + @first_client_hello = client_hello + @first_selection = selection + @stage = Stage::ReadingSecondClientHello + end + + private def handle_second_client_hello(message : Bytes) : Nil + first_client_hello = @first_client_hello || raise HandshakeError.new("no first ClientHello") + first_selection = @first_selection || raise HandshakeError.new("no first selection") + second_client_hello = decode_client_hello(message) + @negotiation.check_second_client_hello(first_client_hello, second_client_hello) + second_selection = @negotiation.select_parameters(second_client_hello, first_selection) + unless second_selection.client_key_share && second_selection.group == first_selection.group && + second_selection.cipher_suite == first_selection.cipher_suite + raise HandshakeError.new("the second ClientHello does not answer the HelloRetryRequest", TLS::AlertDescription::IllegalParameter) + end + # The certificate was chosen by the first ClientHello's name. + unless second_selection.server_name == first_selection.server_name + raise HandshakeError.new("the second ClientHello names another server", TLS::AlertDescription::IllegalParameter) + end + accept_quic_selection(second_selection) + @first_client_hello = nil + @first_selection = nil + answer_client_hello(second_client_hello, message, second_selection) + end + + # Decodes a ClientHello and makes the TLS checks and RFC 9001's. + private def decode_client_hello(message : Bytes) : TLS::Messages::ClientHello + expect_type(message, TLS::HandshakeType::ClientHello) + client_hello = TLS::Messages::ClientHello.decode(TLS::Messages.unwrap(message)[1]) + @negotiation.check_client_hello(client_hello) + # The middlebox compatibility mode has no place in QUIC (§8.4). + unless client_hello.legacy_session_id.empty? + raise HandshakeError.new("a ClientHello with a legacy_session_id", TLS::AlertDescription::IllegalParameter, + HandshakeError::PROTOCOL_VIOLATION) + end + transport_parameters = client_hello.extension(TLS::ExtensionType::QuicTransportParameters) + unless transport_parameters + raise HandshakeError.new("a ClientHello without quic_transport_parameters", TLS::AlertDescription::MissingExtension) + end + @peer_transport_parameters = transport_parameters.dup + client_hello + end + + # QUIC needs an agreed application protocol (§8.1). + private def accept_quic_selection(selection : Selection) : Nil + alpn_protocol = selection.alpn_protocol + unless alpn_protocol + raise HandshakeError.new("no ALPN protocol was agreed", TLS::AlertDescription::NoApplicationProtocol) + end + @alpn_protocol = alpn_protocol + @server_name = selection.server_name + end + + # Writes the ServerHello and the server's Handshake flight, and + # installs the Handshake and Application keys. + private def answer_client_hello(client_hello : TLS::Messages::ClientHello, message : Bytes, selection : Selection) : Nil + cipher_suite = selection.cipher_suite + hash = cipher_suite.hash_algorithm + certified_key = @context.certified_key_for_server_name(selection.server_name) + # The CertificateVerify scheme is chosen before the ServerHello, so a + # client that offers none of this key's schemes is refused in the clear. + list_of_offered_schemes = client_hello.extension(TLS::ExtensionType::SignatureAlgorithms).try { |contents| ExtensionCodec.decode_u16_list(contents) } || [] of UInt16 + certificate_scheme = certified_key.signature_scheme_for(list_of_offered_schemes) || + raise HandshakeError.new("the client offers no signature scheme this server's key signs", TLS::AlertDescription::HandshakeFailure) + @transcript.add(message) + ensure_level_is_consumed(EncryptionLevel::Initial, "Initial data the handshake did not read when the Handshake keys arrived", + TLS::AlertDescription::UnexpectedMessage, HandshakeError::PROTOCOL_VIOLATION) + + client_key_share = selection.client_key_share || raise HandshakeError.new("no client key share") + key_exchange_response = TLS::KeyExchange.respond(selection.group, client_key_share, @randomness) + shared_secret = @secrets.held(key_exchange_response.shared_secret) + server_hello = TLS::Messages::ServerHello.new(@randomness.random_bytes(32), client_hello.legacy_session_id, cipher_suite.value, [ + TLS::Messages::Extension.new(TLS::ExtensionType::KeyShare.value, ExtensionCodec.encode_server_key_share( + ExtensionCodec::KeyShareEntry.new(selection.group.value, key_exchange_response.server_key_exchange))), + TLS::Messages::Extension.new(TLS::ExtensionType::SupportedVersions.value, ExtensionCodec.encode_selected_version(TLS::ProtocolVersion::TLS_1_3)), + ]).encode + write_and_record(EncryptionLevel::Initial, server_hello) + + schedule = @secrets.held(TLS::KeySchedule.new(hash)) + schedule.enter_handshake_stage(shared_secret) + Crypto::SecretWiping.wipe(shared_secret) + handshake_digest = @transcript.digest(hash) + client_handshake_secret = @secrets.held(schedule.client_handshake_traffic_secret(handshake_digest)) + server_handshake_secret = @secrets.held(schedule.server_handshake_traffic_secret(handshake_digest)) + install_keys(EncryptionLevel::Handshake, cipher_suite, client_handshake_secret, server_handshake_secret) + + list_of_encrypted_extensions = [] of TLS::Messages::Extension + if selection.server_name + list_of_encrypted_extensions << TLS::Messages::Extension.new(TLS::ExtensionType::ServerName.value, Bytes.empty) + end + if alpn_protocol = selection.alpn_protocol + list_of_encrypted_extensions << TLS::Messages::Extension.new(TLS::ExtensionType::ApplicationLayerProtocolNegotiation.value, + ExtensionCodec.encode_protocol_names([alpn_protocol])) + end + list_of_encrypted_extensions << TLS::Messages::Extension.new(TLS::ExtensionType::QuicTransportParameters.value, @local_transport_parameters) + write_and_record(EncryptionLevel::Handshake, TLS::Messages::EncryptedExtensions.new(list_of_encrypted_extensions).encode) + + list_of_entries = certified_key.list_of_certificates.map { |certificate| TLS::Messages::CertificateEntry.new(certificate.encoded, [] of TLS::Messages::Extension) } + write_and_record(EncryptionLevel::Handshake, TLS::Messages::CertificateMessage.new(Bytes.empty, list_of_entries).encode) + signed_content = TLS::Messages::CertificateVerify.signed_content(@transcript.digest(hash), is_server: true) + signature = certified_key.sign(certificate_scheme, signed_content, @randomness) + write_and_record(EncryptionLevel::Handshake, TLS::Messages::CertificateVerify.new(certificate_scheme.value, signature).encode) + server_verify_data = TLS::KeySchedule.finished_verify_data(hash, server_handshake_secret, @transcript.digest(hash)) + write_and_record(EncryptionLevel::Handshake, TLS::Messages::Finished.new(server_verify_data).encode) + + schedule.enter_master_stage + application_digest = @transcript.digest(hash) + client_application_secret = @secrets.held(schedule.client_application_traffic_secret(application_digest)) + server_application_secret = @secrets.held(schedule.server_application_traffic_secret(application_digest)) + install_keys(EncryptionLevel::Application, cipher_suite, client_application_secret, server_application_secret) + # No session tickets and no exporter, so the schedule has nothing + # left to derive. + schedule.wipe + + @cipher_suite = cipher_suite + @client_handshake_traffic_secret = client_handshake_secret + @stage = Stage::ReadingClientFinished + end + + private def handle_client_finished(message : Bytes) : Nil + cipher_suite = @cipher_suite || raise HandshakeError.new("no cipher suite was chosen") + client_handshake_secret = @client_handshake_traffic_secret || raise HandshakeError.new("no client handshake secret") + hash = cipher_suite.hash_algorithm + expect_type(message, TLS::HandshakeType::Finished) + finished = TLS::Messages::Finished.decode(TLS::Messages.unwrap(message)[1], hash.bytesize) + unless TLS::KeySchedule.finished_matches?(hash, client_handshake_secret, @transcript.digest(hash), finished.verify_data) + raise HandshakeError.new("the client's Finished does not verify", TLS::AlertDescription::DecryptError) + end + ensure_level_is_consumed(EncryptionLevel::Handshake, "Handshake data after the client's Finished", + TLS::AlertDescription::UnexpectedMessage, HandshakeError::PROTOCOL_VIOLATION) + @transcript.clear + @stage = Stage::Complete + wipe + end + + private def install_keys(level : EncryptionLevel, cipher_suite : TLS::CipherSuite, client_secret : Bytes, server_secret : Bytes) : Nil + read_protection = PacketProtection.new(cipher_suite, client_secret) + write_protection = PacketProtection.new(cipher_suite, server_secret) + @list_of_installed_keys << InstalledKeys.new(level, read_protection, write_protection) + end + + private def write_and_record(level : EncryptionLevel, message : Bytes) : Nil + @list_of_bytes_to_send_by_level[level.value].write(message) + @transcript.add(message) + end + + private def expect_type(message : Bytes, expected : TLS::HandshakeType) : Nil + actual = TLS::Messages.unwrap(message)[0] + unless actual == expected + raise HandshakeError.new("#{actual || "an unknown handshake message"} arrived where #{expected} was expected", TLS::AlertDescription::UnexpectedMessage) + end + end + + # Raises unless every byte that arrived at *level* was read: a message + # may not straddle a key change (RFC 9001 §4.1.3). + private def ensure_level_is_consumed(level : EncryptionLevel, message : String, alert_description : TLS::AlertDescription, + transport_error_code : UInt64?) : Nil + return if @list_of_received_bytes_by_level[level.value].size == 0 + raise HandshakeError.new(message, alert_description, transport_error_code) + end + end +end diff --git a/src/beryl/tls/protocol.cr b/src/beryl/tls/protocol.cr index b8368cd..0712010 100644 --- a/src/beryl/tls/protocol.cr +++ b/src/beryl/tls/protocol.cr @@ -29,32 +29,35 @@ module Beryl::TLS # RFC 7301, RFC 8449). Any other value is carried as an unknown # extension and ignored where RFC 9846 allows it. enum ExtensionType : UInt16 - ServerName = 0 - MaxFragmentLength = 1 - StatusRequest = 5 - SupportedGroups = 10 - SignatureAlgorithms = 13 - UseSrtp = 14 - Heartbeat = 15 - ApplicationLayerProtocolNegotiation = 16 - SignedCertificateTimestamp = 18 - ClientCertificateType = 19 - ServerCertificateType = 20 - Padding = 21 - ExtendedMasterSecret = 23 - RecordSizeLimit = 28 - SessionTicket = 35 - PreSharedKey = 41 - EarlyData = 42 - SupportedVersions = 43 - Cookie = 44 - PskKeyExchangeModes = 45 - CertificateAuthorities = 47 - OidFilters = 48 - PostHandshakeAuth = 49 - SignatureAlgorithmsCert = 50 - KeyShare = 51 - RenegotiationInfo = 65281 + ServerName = 0 + MaxFragmentLength = 1 + StatusRequest = 5 + SupportedGroups = 10 + SignatureAlgorithms = 13 + UseSrtp = 14 + Heartbeat = 15 + ApplicationLayerProtocolNegotiation = 16 + SignedCertificateTimestamp = 18 + ClientCertificateType = 19 + ServerCertificateType = 20 + Padding = 21 + ExtendedMasterSecret = 23 + RecordSizeLimit = 28 + SessionTicket = 35 + PreSharedKey = 41 + EarlyData = 42 + SupportedVersions = 43 + Cookie = 44 + PskKeyExchangeModes = 45 + CertificateAuthorities = 47 + OidFilters = 48 + PostHandshakeAuth = 49 + SignatureAlgorithmsCert = 50 + KeyShare = 51 + # The QUIC transport parameters (RFC 9001 §8.2), read and written only + # by `Beryl::QUIC::ServerHandshake`. + QuicTransportParameters = 57 + RenegotiationInfo = 65281 end # The TLS 1.3 cipher suites (RFC 9846 §B.4). Beryl offers the first From 21a5285f5cb0dee9e1bb1fa3855a7d5521e8f8f4 Mon Sep 17 00:00:00 2001 From: crimson-knight Date: Sun, 6 Dec 2026 07:36:29 -0500 Subject: [PATCH 3/5] Add an allocation-free header protection mask PacketProtection#header_protection_mask(sample, into: mask) writes the 5-byte mask into the caller's storage, so a transport's per-packet path allocates nothing; the allocating form stays. --- spec/beryl/quic/packet_protection_spec.cr | 11 +++++++++++ src/beryl/quic/header_protection_key.cr | 13 +++++++++++-- src/beryl/quic/packet_protection.cr | 8 ++++++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/spec/beryl/quic/packet_protection_spec.cr b/spec/beryl/quic/packet_protection_spec.cr index 5f289fe..72b63a8 100644 --- a/spec/beryl/quic/packet_protection_spec.cr +++ b/spec/beryl/quic/packet_protection_spec.cr @@ -238,6 +238,17 @@ describe Beryl::QUIC::PacketProtection do it "computes the published header protection mask" do protection = Beryl::QUIC::PacketProtection.new(Beryl::TLS::CipherSuite::TLS_CHACHA20_POLY1305_SHA256, Rfc9001Appendix::CHACHA20_SECRET) protection.header_protection_mask(Rfc9001Appendix::CHACHA20_SAMPLE).should eq(Rfc9001Appendix::CHACHA20_MASK) + mask = Bytes.new(5, 0xaa_u8) + protection.header_protection_mask(Rfc9001Appendix::CHACHA20_SAMPLE, into: mask) + mask.should eq(Rfc9001Appendix::CHACHA20_MASK) + end + + it "writes the AES header protection mask into caller storage" do + read_protection, _ = Beryl::QUIC::PacketProtection.initial_pair_for_server(Rfc9001Appendix::DESTINATION_CONNECTION_ID) + mask = Bytes.new(5, 0xaa_u8) + read_protection.header_protection_mask(Rfc9001Appendix::CLIENT_INITIAL_SAMPLE, into: mask) + mask.should eq(Rfc9001Appendix::CLIENT_INITIAL_MASK) + expect_raises(Beryl::Crypto::OutputSizeMismatch) { read_protection.header_protection_mask(Rfc9001Appendix::CLIENT_INITIAL_SAMPLE, into: Bytes.new(4)) } end it "protects the packet into the published 21 bytes and opens it again" do diff --git a/src/beryl/quic/header_protection_key.cr b/src/beryl/quic/header_protection_key.cr index 9832bd5..92313e5 100644 --- a/src/beryl/quic/header_protection_key.cr +++ b/src/beryl/quic/header_protection_key.cr @@ -51,20 +51,29 @@ module Beryl::QUIC # counter the sample's first four bytes (little-endian) and its nonce # the other twelve, over five zero bytes (§5.4.4). def mask(sample : Bytes) : Bytes + mask = Bytes.new(MASK_BYTESIZE) + mask(sample, into: mask) + mask + end + + # Writes the mask for *sample* into *mask* (5 bytes), allocating nothing. + def mask(sample : Bytes, *, into mask : Bytes) : Nil raise Crypto::KeyWiped.new("the header protection key was wiped") if @generation_count == 0 unless sample.size == SAMPLE_BYTESIZE raise ArgumentError.new("a header protection sample is #{SAMPLE_BYTESIZE} bytes, not #{sample.size}") end - mask = Bytes.new(MASK_BYTESIZE) + unless mask.size == MASK_BYTESIZE + raise Crypto::OutputSizeMismatch.new("a header protection mask is #{MASK_BYTESIZE} bytes, the buffer holds #{mask.size}") + end Crypto::DataIndependentTiming.run do if @cipher_suite.tls_chacha20_poly1305_sha256? + mask.fill(0_u8) counter = IO::ByteFormat::LittleEndian.decode(UInt32, sample[0, 4]) Crypto::V1::ChaCha20StreamCipher.xor_keystream(@chacha20_key, sample[4, 12], counter, mask, mask) else write_aes_mask(sample, mask) end end - mask end # Notes one more `PacketProtection` generation holding this key. diff --git a/src/beryl/quic/packet_protection.cr b/src/beryl/quic/packet_protection.cr index b54b39a..a600197 100644 --- a/src/beryl/quic/packet_protection.cr +++ b/src/beryl/quic/packet_protection.cr @@ -135,6 +135,14 @@ module Beryl::QUIC @header_protection_key.mask(sample) end + # Writes the mask for *sample* into *mask*, which holds 5 bytes, as + # `header_protection_mask` returns it; allocates nothing, for a + # transport's per-packet path. + def header_protection_mask(sample : Bytes, into mask : Bytes) : Nil + raise Crypto::KeyWiped.new("this packet protection was wiped") if @is_wiped + @header_protection_key.mask(sample, into: mask) + end + # Returns the next key phase's protection (§6.1): the traffic secret # moved forward with the label `quic ku`, and the same header # protection key. This generation stays usable until it is wiped. From b5f8cea078ad20514623d8b579133effc491ea8e Mon Sep 17 00:00:00 2001 From: crimson-knight Date: Sun, 6 Dec 2026 09:53:43 -0500 Subject: [PATCH 4/5] =?UTF-8?q?TLS=20server:=20refuse=20quic=5Ftransport?= =?UTF-8?q?=5Fparameters=20over=20TCP=20(RFC=209001=20=C2=A78.2)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit NegotiateParametersFromClientHello now takes the transport it serves (Transport::TCP or Transport::QUIC). Over TCP a ClientHello carrying quic_transport_parameters (0x39) ends with unsupported_extension; the QUIC server handshake passes Transport::QUIC and still requires the extension itself, as before. A new handshake spec sends the client's own ClientHello with 0x39 added and checks the alert on the wire. --- CHANGELOG.md | 5 ++++- spec/beryl/tls/handshake_spec.cr | 20 ++++++++++++++++++ src/beryl/quic/server_handshake.cr | 2 +- .../negotiate_parameters_from_client_hello.cr | 21 ++++++++++++++++--- src/beryl/tls/server_handshake.cr | 2 +- 5 files changed, 44 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index afaadcf..91c74a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,7 +22,10 @@ - TLS: the ClientHello checks and the choice of suite, group, ALPN protocol and server name moved from `ServerHandshake` into `NegotiateParametersFromClientHello`, which the TLS and QUIC servers - share, so the two choose alike. The TLS server behaves as before. + share, so the two choose alike. Told which transport it serves, it has + the TLS server refuse a ClientHello carrying `quic_transport_parameters` + with `unsupported_extension` (RFC 9001 §8.2); otherwise the TLS server + behaves as before. ## 0.2.8 (2026-12-05) diff --git a/spec/beryl/tls/handshake_spec.cr b/spec/beryl/tls/handshake_spec.cr index 4b0915b..99eadf6 100644 --- a/spec/beryl/tls/handshake_spec.cr +++ b/spec/beryl/tls/handshake_spec.cr @@ -689,6 +689,26 @@ describe "Beryl::TLS handshakes over a socket pair" do error.alert_description.should eq(TLS::AlertDescription::ProtocolVersion) io.output.to_slice.should eq(Bytes[21, 3, 3, 0, 2, 2, 70]) end + + it "refuses a ClientHello carrying quic_transport_parameters (unsupported_extension, RFC 9001 §8.2)" do + client_output = TlsHarness::ScriptedIO.new(Bytes.empty) + expect_raises(IO::EOFError) do + TLS::Socket::Client.new(client_output, TlsHarness.client_context, hostname: "localhost") + end + # The client's own ClientHello, past its record header, with the QUIC + # extension added first so pre_shared_key could still come last. + client_hello_message = client_output.output.to_slice[5..] + client_hello = TLS::Messages::ClientHello.decode(TLS::Messages.unwrap(client_hello_message)[1]) + quic_transport_parameters = TLS::Messages::Extension.new(TLS::ExtensionType::QuicTransportParameters.value, Bytes[0x01, 0x02, 0x40, 0x64]) + client_hello.list_of_extensions.unshift(quic_transport_parameters) + message_with_quic_extension = client_hello.encode + record_length = message_with_quic_extension.size + record = Bytes[22, 3, 1, (record_length >> 8).to_u8, (record_length & 0xff).to_u8] + message_with_quic_extension + io = TlsHarness::ScriptedIO.new(record) + error = expect_raises(TLS::Error) { TLS::Socket::Server.new(io, TlsHarness.server_context) } + error.alert_description.should eq(TLS::AlertDescription::UnsupportedExtension) + io.output.to_slice.should eq(Bytes[21, 3, 3, 0, 2, 2, 110]) + end end context "record_size_limit (RFC 8449)" do diff --git a/src/beryl/quic/server_handshake.cr b/src/beryl/quic/server_handshake.cr index cc7eeb8..7e0708c 100644 --- a/src/beryl/quic/server_handshake.cr +++ b/src/beryl/quic/server_handshake.cr @@ -75,7 +75,7 @@ module Beryl::QUIC raise ArgumentError.new("the QUIC server handshake does not request client certificates") end @randomness = @context.randomness - @negotiation = TLS::NegotiateParametersFromClientHello.new(@context) + @negotiation = TLS::NegotiateParametersFromClientHello.new(@context, transport: TLS::NegotiateParametersFromClientHello::Transport::QUIC) end # Takes the next contiguous CRYPTO bytes the client sent at *level*, in diff --git a/src/beryl/tls/negotiate_parameters_from_client_hello.cr b/src/beryl/tls/negotiate_parameters_from_client_hello.cr index 188caa5..cc80b1f 100644 --- a/src/beryl/tls/negotiate_parameters_from_client_hello.cr +++ b/src/beryl/tls/negotiate_parameters_from_client_hello.cr @@ -11,10 +11,18 @@ module Beryl::TLS # and the QUIC one (`Beryl::QUIC::ServerHandshake`) use it, so the two # can never choose differently. One instance serves one handshake: it # asks the ALPN chooser once and keeps the answer for a second - # ClientHello. + # ClientHello. The transport it serves decides whether the + # `quic_transport_parameters` extension belongs in a ClientHello. class NegotiateParametersFromClientHello alias ExtensionCodec = Messages::ExtensionCodec + # What carries the handshake: TLS records over a byte stream, or QUIC + # CRYPTO frames (RFC 9001). + enum Transport + TCP + QUIC + end + # The choices made from one ClientHello. record Selection, cipher_suite : CipherSuite, @@ -26,10 +34,11 @@ module Beryl::TLS @list_of_alpn_protocols_to_offer : Array(String)? = nil - def initialize(@context : Context::Server) + def initialize(@context : Context::Server, *, @transport : Transport) end - # The checks on any ClientHello (§4.1.2, §4.2, §9.2). + # The checks on any ClientHello (§4.1.2, §4.2, §9.2, and RFC 9001 + # §8.2 over TCP). def check_client_hello(client_hello : Messages::ClientHello) : Nil # SSL 3.0 and older are never negotiated (Appendix D.5), so such a # legacy_version is no TLS 1.3 ClientHello. @@ -49,6 +58,12 @@ module Beryl::TLS raise Error.new("pre_shared_key is not the last extension", AlertDescription::IllegalParameter) end end + # quic_transport_parameters has no meaning outside QUIC, so a TLS + # server over TCP refuses it (RFC 9001 §8.2). The QUIC server requires + # it, in `Beryl::QUIC::ServerHandshake`. + if @transport.tcp? && client_hello.has_extension?(ExtensionType::QuicTransportParameters) + raise Error.new("quic_transport_parameters in a ClientHello over TCP", AlertDescription::UnsupportedExtension) + end has_key_share = client_hello.has_extension?(ExtensionType::KeyShare) has_groups = client_hello.has_extension?(ExtensionType::SupportedGroups) if has_key_share != has_groups diff --git a/src/beryl/tls/server_handshake.cr b/src/beryl/tls/server_handshake.cr index 4145ce4..ebabed5 100644 --- a/src/beryl/tls/server_handshake.cr +++ b/src/beryl/tls/server_handshake.cr @@ -37,7 +37,7 @@ module Beryl::TLS def initialize(@record_layer : RecordLayer, @context : Context::Server) @randomness = @context.randomness - @negotiation = NegotiateParametersFromClientHello.new(@context) + @negotiation = NegotiateParametersFromClientHello.new(@context, transport: NegotiateParametersFromClientHello::Transport::TCP) end # Runs the handshake. Every secret it derived and does not hand on is From 1497992b878d1b5ca8159ca2093af43a81c9c011 Mon Sep 17 00:00:00 2001 From: crimson-knight Date: Sun, 6 Dec 2026 09:53:44 -0500 Subject: [PATCH 5/5] Secret-flow probes: cover QUIC header protection spec/probes/secret_flow.cr gains header_protection_keying (the quic hp key from a secret traffic secret) and header_protection_mask (the mask the check follows out of the key), run under every suite; secret_taint.cr runs the same under Memcheck. check_secret_flow.rb analyzes Beryl::QUIC::HeaderProtectionKey as a cipher object, and now treats the buffers of a cipher object passed to a probe entry point as key material: the mask was inlined into the probe, so the self-only rule missed a branch planted on the ChaCha20 key; with this change the planted branch is reported and the real code passes. --- CHANGELOG.md | 5 +++++ scripts/check_secret_flow.rb | 22 +++++++++++++++++----- spec/probes/secret_flow.cr | 26 ++++++++++++++++++++++++++ spec/probes/secret_taint.cr | 17 +++++++++++++++++ 4 files changed, 65 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 91c74a9..350b258 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,11 @@ the TLS server refuse a ClientHello carrying `quic_transport_parameters` with `unsupported_extension` (RFC 9001 §8.2); otherwise the TLS server behaves as before. +- Secret-flow checks: QUIC header protection (keying from a traffic secret, + and the mask) joins `spec/probes/secret_flow.cr` and + `spec/probes/secret_taint.cr`. `scripts/check_secret_flow.rb` now also + treats the buffers of a cipher object passed to a probe entry point as + key material, so a method the optimizer inlined there is still checked. ## 0.2.8 (2026-12-05) diff --git a/scripts/check_secret_flow.rb b/scripts/check_secret_flow.rb index 925ed09..95aa760 100644 --- a/scripts/check_secret_flow.rb +++ b/scripts/check_secret_flow.rb @@ -54,7 +54,7 @@ # field. The memory-checker run (spec/probes/secret_taint.cr under Valgrind) # and the timing check cover the same code by two other methods. -ANALYZED_FUNCTION = /Beryl::Crypto|SecretFlowProbe|Crypto::Subtle/.freeze +ANALYZED_FUNCTION = /Beryl::Crypto|Beryl::QUIC::HeaderProtectionKey|SecretFlowProbe|Crypto::Subtle/.freeze # Functions whose every pointer argument leads to secret memory: the cipher # and authenticator cores, which work on keys, round keys, accumulators and @@ -70,11 +70,12 @@ MontgomeryArithmetic::|KeccakPermutation::| ModuleLatticeKeyEncapsulation768::PolynomialRing::(?!sample_ntt|decode_12_below_modulus)/x.freeze -# Methods of the cipher objects. A cipher object keeps integers that are -# public (a round count, a tag size) beside buffers that are secret (a key, +# Methods of the cipher objects, QUIC's header protection key among them. +# A cipher object keeps integers that are public (a round count, a tag size, +# a cipher suite, a generation count) beside buffers that are secret (a key, # round keys, a hash key), so every buffer loaded from the object is secret # and its integers are not. -CIPHER_OBJECT_METHOD = /AuthenticatedEncryption|GaloisCounterMode|CipherBlockChainingMode|RivestShamirAdleman::/.freeze +CIPHER_OBJECT_METHOD = /AuthenticatedEncryption|GaloisCounterMode|CipherBlockChainingMode|RivestShamirAdleman::|QUIC::HeaderProtectionKey/.freeze # Functions of the elliptic-curve code that take secrets by value: field # elements and scalars as arrays of limbs, points as structs of them, a @@ -279,6 +280,17 @@ def initialize(function, state_paths_by_compression_function) @is_compression = function.name.match?(COMPRESSION_FUNCTION) @is_secret_buffer_function = function.name.match?(SECRET_BUFFER_FUNCTION) @is_cipher_object_method = function.name.match?(CIPHER_OBJECT_METHOD) + # The cipher objects whose buffers hold key material: `self` in one of + # their methods, and the object a probe entry point takes, where the + # optimizer may have inlined the method (a probe passes its slices by + # value, so its pointer arguments are the objects). + @list_of_cipher_object_pointers = if @is_cipher_object_method && function.name.include?("SecretFlowProbe::") + function.parameters.select { |_name, kind| kind == :pointer }.keys + elsif @is_cipher_object_method + ["%self"] + else + [] + end @is_secret_value_function = function.name.match?(SECRET_VALUE_FUNCTION) # A public argument passed as a Slice (an exponent) is not secret memory. if @is_secret_value_function @@ -385,7 +397,7 @@ def visit(instruction) elsif instruction.text.start_with?("load ptr") @origin[instruction.result] = [instruction.result, ""] # A buffer that a cipher object owns holds key material. - @secret_bases[instruction.result] = true if @is_cipher_object_method && pointer && @origin[pointer]&.first == "%self" + @secret_bases[instruction.result] = true if pointer && @list_of_cipher_object_pointers.include?(@origin[pointer]&.first) end when "store" value_text, pointer = instruction.text.sub(/\Astore (?:volatile )?/, "").split(", ptr ", 2) diff --git a/spec/probes/secret_flow.cr b/spec/probes/secret_flow.cr index d009b7a..8b0dfbc 100644 --- a/spec/probes/secret_flow.cr +++ b/spec/probes/secret_flow.cr @@ -11,6 +11,7 @@ # `leaky_table_selection`, `leaky_limb_lookup` and `leaky_flags_clobber` are # the faults the check exists to catch and must be reported. require "../../src/beryl/crypto" +require "../../src/beryl/quic/header_protection_key" require "../support/wycheproof" module SecretFlowProbe @@ -136,6 +137,22 @@ module SecretFlowProbe Beryl::Crypto.decrypt(encrypted_message, key: key) end + alias HeaderProtectionKey = Beryl::QUIC::HeaderProtectionKey + + # QUIC header protection (RFC 9001 §5.4), keyed like the ciphers above: + # the traffic secret the "quic hp" key is expanded from is the secret, + # the sample stands in for ciphertext, and the mask is the derived value + # the check follows out of the key's AES round keys or ChaCha20 key. + @[NoInline] + def self.header_protection_keying(cipher_suite : Beryl::TLS::CipherSuite, traffic_secret : Bytes) : HeaderProtectionKey + HeaderProtectionKey.new(cipher_suite, traffic_secret) + end + + @[NoInline] + def self.header_protection_mask(header_protection_key : HeaderProtectionKey, sample : Bytes, mask : Bytes) : Nil + header_protection_key.mask(sample, into: mask) + end + alias X25519 = Beryl::Crypto::V1::X25519 alias Ed25519 = Beryl::Crypto::V1::Ed25519 alias P256 = Beryl::Crypto::V1::P256 @@ -342,6 +359,15 @@ is_verified &= opened == plaintext SecretFlowProbe.aes_block_decryption(round_keys, key_bytesize // 4 + 6, ciphertext[0, 64], opened[0, 64]) SecretFlowProbe.leaky_comparison_of_round_keys(round_keys) end +# QUIC header protection under each suite, from a traffic secret of the +# suite's hash size. +header_protection_mask = Bytes.new(SecretFlowProbe::HeaderProtectionKey::MASK_BYTESIZE) +Beryl::TLS::CipherSuite.each do |cipher_suite| + traffic_secret = Bytes.new(cipher_suite.hash_algorithm.bytesize) { |index| (index &+ 5).to_u8! } + header_protection_key = SecretFlowProbe.header_protection_keying(cipher_suite, traffic_secret) + SecretFlowProbe.header_protection_mask(header_protection_key, plaintext[0, SecretFlowProbe::HeaderProtectionKey::SAMPLE_BYTESIZE], header_protection_mask) + header_protection_key.release +end is_verified &= SecretFlowProbe.leaky_table_selection(Slice(UInt64).new(16) { |index| index.to_u64 }, key) == key[0].to_u64 & 0x0f_u64 # The public-key operations on secret scalars, seeds and messages. The peer diff --git a/spec/probes/secret_taint.cr b/spec/probes/secret_taint.cr index 666aa39..e0265e2 100644 --- a/spec/probes/secret_taint.cr +++ b/spec/probes/secret_taint.cr @@ -19,6 +19,7 @@ # for what is defined, out of the report. Linux only: Valgrind does not run # on macOS arm64. require "../../src/beryl/crypto" +require "../../src/beryl/quic/header_protection_key" # Returns *word_count* words that Memcheck treats as secret. def secret_words(word_count : Int32) : Slice(UInt64) @@ -259,6 +260,22 @@ LIST_OF_MESSAGE_BYTESIZES.each do |bytesize| keep(result_storage, tag) end +# QUIC header protection (RFC 9001 §5.4) under each suite: the "quic hp" +# key is expanded from a secret traffic secret, and the mask over a sample +# (ciphertext, public in a packet, secret here to make the check stricter) +# is the value that follows from it. The key is used and released twice, +# as two generations of packet protection share it. +Beryl::TLS::CipherSuite.each do |cipher_suite| + header_protection_key = Beryl::QUIC::HeaderProtectionKey.new(cipher_suite, secret_bytes(cipher_suite.hash_algorithm.bytesize)) + header_protection_key.share + header_protection_mask = Bytes.new(Beryl::QUIC::HeaderProtectionKey::MASK_BYTESIZE) + header_protection_key.mask(secret_bytes(Beryl::QUIC::HeaderProtectionKey::SAMPLE_BYTESIZE), into: header_protection_mask) + keep(result_storage, header_protection_mask) + keep(result_storage, header_protection_key.mask(secret_bytes(Beryl::QUIC::HeaderProtectionKey::SAMPLE_BYTESIZE))) + header_protection_key.release + header_protection_key.release +end + # The public-key operations: secret scalars, seeds and messages; public # peer keys. The build leaves the Data Independent Timing mode alone (see # `ProcessorFeatures`), so `DataIndependentTiming.run` is only its block.