From ca91d48c385f7d16ad3993ecaf26fa9b84882dbc Mon Sep 17 00:00:00 2001 From: Anton Malygin Date: Tue, 10 Nov 2026 09:46:01 -0600 Subject: [PATCH] client: answer a HelloRetryRequest as uTLS does A ClientHelloPlan is built once per connection and applied to the second ClientHello a HelloRetryRequest asks for as well. Two of its parts did not fit that flight: - A retry that names a group must carry a single key share for it (RFC 8446 section 4.1.2), the one rustls makes in retry_key_share. The plan's raw key shares and its GREASE key share were added beside it, and OpenSSL and Go's crypto/tls refuse such a ClientHello with illegal_parameter. They now belong to the first ClientHello alone; a retry that carries only a cookie repeats them, as it must repeat the key share list. - PadToHandshakeSize pads every flight to the first one's target. ClientHelloPaddingPlan::boringssl(offset) applies BoringSSL's padding rule (ssl_add_clienthello_tlsext, uTLS's BoringPaddingStyle) to each ClientHello as it is encoded: a handshake message of 256 to 511 bytes before padding is padded up to 512, or by one byte when the extension header alone would reach 512, and any other carries no padding extension. offset is added to the measured length and to the padding, for a ClientHello that many bytes shorter than the one it stands for. A HelloRetryRequest's cookie needs no change here: a planned extension order may name the cookie, and PlannedExtensionOrder drops it from a ClientHello that carries none. Tests drive a connection through a scripted HelloRetryRequest naming a group (GREASE as a raw share and through the GREASE plan), one carrying a cookie, and BoringSSL padding across both flights. --- rustls/src/client/client_hello.rs | 51 ++++++ rustls/src/client/hs.rs | 63 +++++-- rustls/src/client/test.rs | 291 ++++++++++++++++++++++++++++++ 3 files changed, 393 insertions(+), 12 deletions(-) diff --git a/rustls/src/client/client_hello.rs b/rustls/src/client/client_hello.rs index 2bdc01f890d..ccbcf231360 100644 --- a/rustls/src/client/client_hello.rs +++ b/rustls/src/client/client_hello.rs @@ -1055,6 +1055,7 @@ fn is_grease_value(value: u16) -> bool { pub(crate) enum ClientHelloPaddingMode { Fixed(u16), PadToHandshakeSize(u16), + BoringSsl { offset: i16 }, } /// Structured control for the ClientHello padding extension. @@ -1084,11 +1085,61 @@ impl ClientHelloPaddingPlan { }) } + /// Pad as BoringSSL pads, on every ClientHello of the connection. + /// + /// BoringSSL (`ssl_add_clienthello_tlsext`), and uTLS's + /// `BoringPaddingStyle` with it, pads a ClientHello whose handshake + /// message is 256 to 511 bytes long before padding: up to 512 bytes, or by + /// a single byte when the four-byte extension header alone would reach + /// 512. Any other ClientHello carries no padding extension at all. The + /// rule is applied to each ClientHello as it is encoded, so the second + /// one a HelloRetryRequest asks for is padded by its own length. + /// + /// `offset` is added to the length the rule reads and to the padding: + /// a ClientHello `offset` bytes shorter than the one it stands for (one + /// leaving out cipher suites this provider cannot negotiate, say) is + /// padded or left alone as that one would be, and when padded comes to + /// its length. A negative `offset` stands for a longer ClientHello; the + /// padding then shrinks by as much, down to an empty extension. + pub fn boringssl(offset: isize) -> Result { + let offset = i16::try_from(offset) + .ok() + .filter(|offset| isize::from(*offset).abs() < BORINGSSL_PADDING_TARGET) + .ok_or_else(|| { + Error::General("ClientHello BoringSSL padding offset is out of range".into()) + })?; + Ok(Self { + mode: ClientHelloPaddingMode::BoringSsl { offset }, + }) + } + pub(crate) fn mode(&self) -> ClientHelloPaddingMode { self.mode } } +/// The handshake message length BoringSSL pads a ClientHello up to. +const BORINGSSL_PADDING_TARGET: isize = 0x200; +/// The shortest handshake message BoringSSL pads. +const BORINGSSL_PADDING_FLOOR: isize = 0x100; + +/// The padding body BoringSSL gives a ClientHello handshake message of +/// `unpadded` bytes, or `None` for one it leaves without the extension +/// (`BoringPaddingStyle` in uTLS: `paddingLen >= 4+1` keeps all but the +/// header, otherwise one byte). +pub(crate) fn boringssl_padding_len(unpadded: isize) -> Option { + const EXTENSION_HEADER_LEN: isize = 4; + if !(BORINGSSL_PADDING_FLOOR..BORINGSSL_PADDING_TARGET).contains(&unpadded) { + return None; + } + let padding = BORINGSSL_PADDING_TARGET - unpadded; + Some(if padding > EXTENSION_HEADER_LEN { + (padding - EXTENSION_HEADER_LEN) as usize + } else { + 1 + }) +} + fn validate_padding_size(size: usize) -> Result { u16::try_from(size) .map_err(|_| Error::General("ClientHello padding size cannot exceed 65535 bytes".into())) diff --git a/rustls/src/client/hs.rs b/rustls/src/client/hs.rs index 5c32a6e526c..daa20695c81 100644 --- a/rustls/src/client/hs.rs +++ b/rustls/src/client/hs.rs @@ -7,7 +7,7 @@ use core::ops::Deref; use pki_types::ServerName; -use super::client_hello::ClientHelloPaddingMode; +use super::client_hello::{ClientHelloPaddingMode, boringssl_padding_len}; #[cfg(feature = "tls12")] use super::tls12; use super::{ResolvesClientCert, Tls12Resumption}; @@ -537,7 +537,8 @@ fn apply_padding_plan( let length = match padding.mode() { ClientHelloPaddingMode::Fixed(length) => length, - ClientHelloPaddingMode::PadToHandshakeSize(_) => 0, + ClientHelloPaddingMode::PadToHandshakeSize(_) + | ClientHelloPaddingMode::BoringSsl { .. } => 0, }; exts.padding = Some(zero_padding(length)); Ok(()) @@ -763,19 +764,45 @@ fn finalize_padding_plan( return Ok(()); }; - if let ClientHelloPaddingMode::PadToHandshakeSize(target_size) = padding.mode() { - payload.extensions.padding = Some(Payload::empty()); - let current_size = encoded_client_hello_len(payload); - let padding_len = usize::from(target_size).saturating_sub(current_size); - let padding_len = u16::try_from(padding_len).map_err(|_| { - Error::General("ClientHello padding size cannot exceed 65535 bytes".into()) - })?; - payload.extensions.padding = Some(zero_padding(padding_len)); + match padding.mode() { + ClientHelloPaddingMode::PadToHandshakeSize(target_size) => { + payload.extensions.padding = Some(Payload::empty()); + let current_size = encoded_client_hello_len(payload); + let padding_len = usize::from(target_size).saturating_sub(current_size); + let padding_len = u16::try_from(padding_len).map_err(|_| { + Error::General("ClientHello padding size cannot exceed 65535 bytes".into()) + })?; + payload.extensions.padding = Some(zero_padding(padding_len)); + } + ClientHelloPaddingMode::BoringSsl { offset } => { + // Measured with an empty extension, then without its header: + // the length BoringSSL reads, less what `offset` stands for. + payload.extensions.padding = Some(Payload::empty()); + let unpadded = encoded_client_hello_len(payload) - PADDING_EXTENSION_HEADER_LEN; + let offset = isize::from(offset); + payload.extensions.padding = match boringssl_padding_len(unpadded as isize + offset) { + // Left out of the encoding: an extension the custom order + // names but the ClientHello does not carry is skipped. + None => None, + Some(padding_len) => { + let padding_len = (padding_len as isize + offset).max(0) as usize; + let padding_len = u16::try_from(padding_len).map_err(|_| { + Error::General("ClientHello padding size cannot exceed 65535 bytes".into()) + })?; + Some(zero_padding(padding_len)) + } + }; + } + ClientHelloPaddingMode::Fixed(_) => {} } Ok(()) } +/// What a padding extension adds to a ClientHello besides its body: its +/// type and length. +const PADDING_EXTENSION_HEADER_LEN: usize = 4; + fn insert_at(items: &mut Vec, position: usize, value: T, what: &str) -> Result<(), Error> { if position > items.len() { return Err(Error::General( @@ -842,6 +869,7 @@ fn apply_grease_plan( exts: &mut ClientExtensions<'_>, cipher_suites: &mut Vec, extension_order: Option<&PlannedExtensionOrder>, + retry_names_group: bool, ) -> Result<(), Error> { let Some(grease) = plan.and_then(|plan| plan.grease.as_ref()) else { return Ok(()); @@ -886,7 +914,10 @@ fn apply_grease_plan( )?; } - if let Some(position) = grease.key_share_position() { + if let Some(position) = grease + .key_share_position() + .filter(|_| !retry_names_group) + { let Some(key_shares) = exts.key_shares.as_mut() else { return Err(Error::General( "ClientHello GREASE key_share requires a key_share extension".into(), @@ -1184,7 +1215,14 @@ fn emit_client_hello_for_retry( apply_advertised_supported_versions_plan(input.plan.as_ref(), &mut exts)?; apply_advertised_supported_groups_plan(input.plan.as_ref(), &mut exts)?; apply_exact_extension_plan(input.plan.as_ref(), &mut exts)?; - apply_raw_key_share_plan(input.plan.as_ref(), &mut exts)?; + // A HelloRetryRequest that names a group gets a single key share from it + // (RFC 8446 section 4.1.2), the one rustls has just made. The planned + // extra shares, raw ones and the GREASE one, belong to the first + // ClientHello; a retry that only carries a cookie repeats them. + let retry_names_group = retryreq.is_some_and(|hrr| hrr.key_share.is_some()); + if !retry_names_group { + apply_raw_key_share_plan(input.plan.as_ref(), &mut exts)?; + } apply_padding_plan(input.plan.as_ref(), &mut exts)?; // Every extension this ClientHello carries is decided by now, so the // planned order can be reconciled with it -- which both the GREASE @@ -1208,6 +1246,7 @@ fn emit_client_hello_for_retry( &mut exts, &mut cipher_suites, extension_order.as_ref(), + retry_names_group, )?; let mut chp_payload = ClientHelloPayload { diff --git a/rustls/src/client/test.rs b/rustls/src/client/test.rs index 9882e18b5f2..15462241f00 100644 --- a/rustls/src/client/test.rs +++ b/rustls/src/client/test.rs @@ -3413,6 +3413,297 @@ fn hybrid_kx_component_share_not_offered_unless_supported_separately() { assert_eq!(key_shares[0].group, NamedGroup::X25519MLKEM768); } +/// A TLS 1.3 config offering X25519 alone in its first ClientHello, with +/// `plan` shaping every ClientHello of the connection. +#[cfg(all(feature = "aws_lc_rs", not(feature = "fips")))] +fn retry_test_config(plan: ClientHelloPlan) -> ClientConfig { + let mut config = + ClientConfig::builder_with_provider(crate::crypto::aws_lc_rs::default_provider().into()) + .with_protocol_versions(&[&crate::version::TLS13]) + .unwrap() + .with_root_certificates(roots()) + .with_no_client_auth(); + config.client_hello_customizer = Some(StdArc::new(StaticClientHelloCustomizer { + plan: Mutex::new(Some(plan.with_key_share_plan( + ClientHelloKeySharePlan::try_from(vec![NamedGroup::X25519]).unwrap(), + ))), + })); + config +} + +/// The two ClientHellos `config` sends around a HelloRetryRequest carrying +/// `extensions` (and TLS 1.3, and the first ClientHello's session id). +#[cfg(all(feature = "aws_lc_rs", not(feature = "fips")))] +fn client_hellos_around_retry( + config: ClientConfig, + extensions: crate::msgs::handshake::HelloRetryRequestExtensions<'static>, +) -> (ClientHelloPayload, ClientHelloPayload) { + let mut conn = + ClientConnection::new(config.into(), ServerName::try_from("localhost").unwrap()).unwrap(); + let mut first_flight = Vec::new(); + conn.write_tls(&mut first_flight) + .unwrap(); + let first = client_hello_in_records(&first_flight); + + let hrr = Message { + version: ProtocolVersion::TLSv1_3, + payload: MessagePayload::handshake(HandshakeMessagePayload( + HandshakePayload::HelloRetryRequest(HelloRetryRequest { + cipher_suite: CipherSuite::TLS13_AES_128_GCM_SHA256, + legacy_version: ProtocolVersion::TLSv1_2, + session_id: first.session_id, + extensions: crate::msgs::handshake::HelloRetryRequestExtensions { + supported_versions: Some(ProtocolVersion::TLSv1_3), + ..extensions + }, + }), + )), + }; + conn.read_tls(&mut hrr.into_wire_bytes().as_slice()) + .unwrap(); + conn.process_new_packets().unwrap(); + let mut second_flight = Vec::new(); + conn.write_tls(&mut second_flight) + .unwrap(); + (first, client_hello_in_records(&second_flight)) +} + +/// The ClientHello among the TLS records in `bytes`, past a +/// middlebox-compatibility ChangeCipherSpec. +#[cfg(all(feature = "aws_lc_rs", not(feature = "fips")))] +fn client_hello_in_records(bytes: &[u8]) -> ClientHelloPayload { + let mut reader = Reader::init(bytes); + loop { + let message = OutboundOpaqueMessage::read(&mut reader) + .unwrap() + .into_plain_message(); + if let Ok(Message { + payload: + MessagePayload::Handshake { + parsed: HandshakeMessagePayload(HandshakePayload::ClientHello(ch)), + .. + }, + .. + }) = Message::try_from(message) + { + return ch; + } + } +} + +#[cfg(all(feature = "aws_lc_rs", not(feature = "fips")))] +fn key_share_groups(ch: &ClientHelloPayload) -> Vec { + ch.extensions + .key_shares + .as_ref() + .unwrap() + .iter() + .map(|share| share.group) + .collect() +} + +/// A HelloRetryRequest that names a group gets one key share from it +/// (RFC 8446 section 4.1.2), whichever way the plan adds a GREASE share to +/// the first ClientHello. OpenSSL and Go's crypto/tls refuse a second +/// ClientHello carrying more with `illegal_parameter`. +#[cfg(all(feature = "aws_lc_rs", not(feature = "fips")))] +#[test] +fn a_retry_naming_a_group_sends_its_key_share_alone() { + let grease = NamedGroup::from(0x0a0a); + for plan in [ + ClientHelloPlan::new().with_raw_key_shares( + ClientHelloRawKeyShares::try_from(vec![ + ClientHelloRawKeyShare::new_at(0, grease, vec![0]).unwrap(), + ]) + .unwrap(), + ), + ClientHelloPlan::new().with_grease( + ClientHelloGreasePlan::new(0x0a0a) + .unwrap() + .with_key_share_position(0), + ), + ] { + let (first, second) = client_hellos_around_retry( + retry_test_config(plan), + crate::msgs::handshake::HelloRetryRequestExtensions { + key_share: Some(NamedGroup::secp256r1), + ..Default::default() + }, + ); + + assert_eq!(key_share_groups(&first), vec![grease, NamedGroup::X25519]); + assert_eq!(key_share_groups(&second), vec![NamedGroup::secp256r1]); + } +} + +/// A HelloRetryRequest with a cookie and no group keeps the first +/// ClientHello's key shares, planned ones included, and the cookie lands +/// where the planned order puts it; the first ClientHello, which has no +/// cookie, leaves that entry out. +#[cfg(all(feature = "aws_lc_rs", not(feature = "fips")))] +#[test] +fn a_retry_with_a_cookie_repeats_the_key_shares_and_takes_its_planned_place() { + let planned = [ + ExtensionType::SupportedVersions, + ExtensionType::Cookie, + ExtensionType::ServerName, + ExtensionType::SignatureAlgorithms, + ExtensionType::EllipticCurves, + ExtensionType::ECPointFormats, + ExtensionType::ExtendedMasterSecret, + ExtensionType::StatusRequest, + ExtensionType::KeyShare, + ExtensionType::PSKKeyExchangeModes, + ]; + let plan = ClientHelloPlan::new() + .with_raw_key_shares( + ClientHelloRawKeyShares::try_from(vec![ + ClientHelloRawKeyShare::new_at(0, NamedGroup::from(0x0a0a), vec![0]).unwrap(), + ]) + .unwrap(), + ) + .with_extension_order( + ClientHelloExtensionOrder::try_from( + planned + .iter() + .map(|extension| u16::from(*extension)) + .collect::>(), + ) + .unwrap(), + ); + let mut config = retry_test_config(plan); + config.cert_decompressors = Vec::new(); + + let (first, second) = client_hellos_around_retry( + config, + crate::msgs::handshake::HelloRetryRequestExtensions { + cookie: Some(PayloadU16::new(vec![1, 2, 3, 4])), + ..Default::default() + }, + ); + + let without_cookie = planned + .iter() + .copied() + .filter(|extension| *extension != ExtensionType::Cookie) + .collect::>(); + assert_eq!( + first + .extensions + .used_extensions_in_encoding_order(), + without_cookie + ); + assert_eq!( + second + .extensions + .used_extensions_in_encoding_order(), + planned.to_vec() + ); + assert_eq!( + second + .extensions + .cookie + .as_ref() + .map(|cookie| cookie.0.clone()), + Some(vec![1, 2, 3, 4]) + ); + let shares = |ch: &ClientHelloPayload| { + ch.extensions + .key_shares + .as_ref() + .unwrap() + .iter() + .map(|share| (share.group, share.payload.0.clone())) + .collect::>() + }; + assert_eq!(shares(&second), shares(&first)); +} + +#[test] +fn boringssl_padding_len_is_boringssls_rule() { + assert_eq!(super::client_hello::boringssl_padding_len(0xff), None); + assert_eq!( + super::client_hello::boringssl_padding_len(0x100), + Some(0x200 - 0x100 - 4) + ); + assert_eq!(super::client_hello::boringssl_padding_len(494), Some(14)); + assert_eq!(super::client_hello::boringssl_padding_len(507), Some(1)); + assert_eq!(super::client_hello::boringssl_padding_len(508), Some(1)); + assert_eq!(super::client_hello::boringssl_padding_len(511), Some(1)); + assert_eq!(super::client_hello::boringssl_padding_len(0x200), None); + assert!(ClientHelloPaddingPlan::boringssl(512).is_err()); + assert!(ClientHelloPaddingPlan::boringssl(-512).is_err()); + assert!(ClientHelloPaddingPlan::boringssl(511).is_ok()); +} + +/// Each ClientHello is padded by its own length: the second ClientHello a +/// HelloRetryRequest asks for, whose P-256 share is 33 bytes longer than +/// the first one's X25519 share, can leave BoringSSL's window the first sat +/// in, and the padding goes with it. BoringSSL's rule is restated here. +#[cfg(all(feature = "aws_lc_rs", not(feature = "fips")))] +#[test] +fn boringssl_padding_follows_each_client_hellos_own_length() { + fn encoded_len(ch: &ClientHelloPayload) -> usize { + let mut bytes = Vec::new(); + HandshakeMessagePayload(HandshakePayload::ClientHello(ch.clone())).encode(&mut bytes); + bytes.len() + } + fn padding_len(ch: &ClientHelloPayload) -> Option { + ch.extensions + .padding + .as_ref() + .map(|padding| padding.bytes().len()) + } + fn unpadded_len(ch: &ClientHelloPayload) -> usize { + encoded_len(ch) - padding_len(ch).map_or(0, |padding| 4 + padding) + } + fn assert_pads_as_boringssl(ch: &ClientHelloPayload, offset: isize, what: &str) { + let imitated = unpadded_len(ch) as isize + offset; + let expected = (256..512).contains(&imitated).then(|| { + let padding = 512 - imitated; + (if padding > 4 { padding - 4 } else { 1 }) + offset + }); + assert_eq!( + padding_len(ch).map(|padding| padding as isize), + expected, + "{what}: {imitated} bytes before padding, offset {offset}" + ); + } + let hellos = |offset: isize| { + client_hellos_around_retry( + retry_test_config( + ClientHelloPlan::new() + .with_padding(ClientHelloPaddingPlan::boringssl(offset).unwrap()), + ), + crate::msgs::handshake::HelloRetryRequestExtensions { + key_share: Some(NamedGroup::secp256r1), + ..Default::default() + }, + ) + }; + + let (first, second) = hellos(0); + let first_len = unpadded_len(&first) as isize; + let growth = unpadded_len(&second) as isize - first_len; + assert_eq!(growth, 65 - 32, "a P-256 share in place of an X25519 one"); + + // Inside the window both times; the first at the one-byte edge; the + // first inside and the second past it; below the window. + for imitated_first in [300, 509, 500, 200] { + let offset = imitated_first - first_len; + let (first, second) = hellos(offset); + assert_pads_as_boringssl(&first, offset, "first ClientHello"); + assert_pads_as_boringssl(&second, offset, "second ClientHello"); + } + let (first, second) = hellos(500 - first_len); + assert!(padding_len(&first).is_some()); + assert_eq!( + padding_len(&second), + None, + "past 511 bytes, no padding extension" + ); +} + #[derive(Debug)] struct StaticClientHelloCustomizer { plan: Mutex>,