rustls/client/ech.rs
1use alloc::boxed::Box;
2use alloc::vec;
3use alloc::vec::Vec;
4
5use pki_types::{DnsName, EchConfigListBytes, ServerName};
6use subtle::ConstantTimeEq;
7
8use crate::CipherSuite::TLS_EMPTY_RENEGOTIATION_INFO_SCSV;
9use crate::client::tls13;
10use crate::crypto::SecureRandom;
11use crate::crypto::hash::Hash;
12use crate::crypto::hpke::{EncapsulatedSecret, Hpke, HpkePublicKey, HpkeSealer, HpkeSuite};
13use crate::hash_hs::{HandshakeHash, HandshakeHashBuffer};
14use crate::log::{debug, trace, warn};
15use crate::msgs::base::{Payload, PayloadU16};
16use crate::msgs::codec::{Codec, Reader};
17use crate::msgs::enums::{ExtensionType, HpkeKem};
18use crate::msgs::handshake::{
19 ClientExtension, ClientHelloPayload, EchConfigContents, EchConfigPayload, Encoding,
20 EncryptedClientHello, EncryptedClientHelloOuter, HandshakeMessagePayload, HandshakePayload,
21 HelloRetryRequest, HpkeKeyConfig, HpkeSymmetricCipherSuite, PresharedKeyBinder,
22 PresharedKeyOffer, Random, ServerHelloPayload, ServerNamePayload,
23};
24use crate::msgs::message::{Message, MessagePayload};
25use crate::msgs::persist;
26use crate::msgs::persist::Retrieved;
27use crate::tls13::key_schedule::{
28 KeyScheduleEarly, KeyScheduleHandshakeStart, server_ech_hrr_confirmation_secret,
29};
30use crate::{
31 AlertDescription, CommonState, EncryptedClientHelloError, Error, PeerIncompatible,
32 PeerMisbehaved, ProtocolVersion, Tls13CipherSuite,
33};
34
35/// Controls how Encrypted Client Hello (ECH) is used in a client handshake.
36#[derive(Clone, Debug)]
37pub enum EchMode {
38 /// ECH is enabled and the ClientHello will be encrypted based on the provided
39 /// configuration.
40 Enable(EchConfig),
41
42 /// No ECH configuration is available but the client should act as though it were.
43 ///
44 /// This is an anti-ossification measure, sometimes referred to as "GREASE"[^0].
45 /// [^0]: <https://www.rfc-editor.org/rfc/rfc8701>
46 Grease(EchGreaseConfig),
47}
48
49impl EchMode {
50 /// Returns true if the ECH mode will use a FIPS approved HPKE suite.
51 pub fn fips(&self) -> bool {
52 match self {
53 Self::Enable(ech_config) => ech_config.suite.fips(),
54 Self::Grease(grease_config) => grease_config.suite.fips(),
55 }
56 }
57}
58
59impl From<EchConfig> for EchMode {
60 fn from(config: EchConfig) -> Self {
61 Self::Enable(config)
62 }
63}
64
65impl From<EchGreaseConfig> for EchMode {
66 fn from(config: EchGreaseConfig) -> Self {
67 Self::Grease(config)
68 }
69}
70
71/// Configuration for performing encrypted client hello.
72///
73/// Note: differs from the protocol-encoded EchConfig (`EchConfigMsg`).
74#[derive(Clone, Debug)]
75pub struct EchConfig {
76 /// The selected EchConfig.
77 pub(crate) config: EchConfigPayload,
78
79 /// An HPKE instance corresponding to a suite from the `config` we have selected as
80 /// a compatible choice.
81 pub(crate) suite: &'static dyn Hpke,
82}
83
84impl EchConfig {
85 /// Construct an EchConfig by selecting a ECH config from the provided bytes that is compatible
86 /// with one of the given HPKE suites.
87 ///
88 /// The config list bytes should be sourced from a DNS-over-HTTPS lookup resolving the `HTTPS`
89 /// resource record for the host name of the server you wish to connect via ECH,
90 /// and extracting the ECH configuration from the `ech` parameter. The extracted bytes should
91 /// be base64 decoded to yield the `EchConfigListBytes` you provide to rustls.
92 ///
93 /// One of the provided ECH configurations must be compatible with the HPKE provider's supported
94 /// suites or an error will be returned.
95 ///
96 /// See the [`ech-client.rs`] example for a complete example of fetching ECH configs from DNS.
97 ///
98 /// [`ech-client.rs`]: https://github.com/rustls/rustls/blob/main/examples/src/bin/ech-client.rs
99 pub fn new(
100 ech_config_list: EchConfigListBytes<'_>,
101 hpke_suites: &[&'static dyn Hpke],
102 ) -> Result<Self, Error> {
103 let ech_configs = Vec::<EchConfigPayload>::read(&mut Reader::init(&ech_config_list))
104 .map_err(|_| {
105 Error::InvalidEncryptedClientHello(EncryptedClientHelloError::InvalidConfigList)
106 })?;
107
108 // Note: we name the index var _i because if the log feature is disabled
109 // it is unused.
110 #[cfg_attr(not(feature = "logging"), allow(clippy::unused_enumerate_index))]
111 for (_i, config) in ech_configs.iter().enumerate() {
112 let contents = match config {
113 EchConfigPayload::V18(contents) => contents,
114 EchConfigPayload::Unknown {
115 version: _version, ..
116 } => {
117 warn!(
118 "ECH config {} has unsupported version {:?}",
119 _i + 1,
120 _version
121 );
122 continue; // Unsupported version.
123 }
124 };
125
126 if contents.has_unknown_mandatory_extension() || contents.has_duplicate_extension() {
127 warn!("ECH config has duplicate, or unknown mandatory extensions: {contents:?}",);
128 continue; // Unsupported, or malformed extensions.
129 }
130
131 let key_config = &contents.key_config;
132 for cipher_suite in &key_config.symmetric_cipher_suites {
133 if cipher_suite.aead_id.tag_len().is_none() {
134 continue; // Unsupported EXPORT_ONLY AEAD cipher suite.
135 }
136
137 let suite = HpkeSuite {
138 kem: key_config.kem_id,
139 sym: *cipher_suite,
140 };
141 if let Some(hpke) = hpke_suites
142 .iter()
143 .find(|hpke| hpke.suite() == suite)
144 {
145 debug!(
146 "selected ECH config ID {:?} suite {:?} public_name {:?}",
147 key_config.config_id, suite, contents.public_name
148 );
149 return Ok(Self {
150 config: config.clone(),
151 suite: *hpke,
152 });
153 }
154 }
155 }
156
157 Err(EncryptedClientHelloError::NoCompatibleConfig.into())
158 }
159
160 /// Compute the HPKE `SetupBaseS` `info` parameter for this ECH configuration.
161 ///
162 /// See <https://datatracker.ietf.org/doc/html/draft-ietf-tls-esni-17#section-6.1>.
163 pub(crate) fn hpke_info(&self) -> Vec<u8> {
164 let mut info = Vec::with_capacity(128);
165 // "tls ech" || 0x00 || ECHConfig
166 info.extend_from_slice(b"tls ech\0");
167 self.config.encode(&mut info);
168 info
169 }
170}
171
172/// Configuration for GREASE Encrypted Client Hello.
173#[derive(Clone, Debug)]
174pub struct EchGreaseConfig {
175 pub(crate) suite: &'static dyn Hpke,
176 pub(crate) placeholder_key: HpkePublicKey,
177}
178
179impl EchGreaseConfig {
180 /// Construct a GREASE ECH configuration.
181 ///
182 /// This configuration is used when the client wishes to offer ECH to prevent ossification,
183 /// but doesn't have a real ECH configuration to use for the remote server. In this case
184 /// a placeholder or "GREASE"[^0] extension is used.
185 ///
186 /// Returns an error if the HPKE provider does not support the given suite.
187 ///
188 /// [^0]: <https://www.rfc-editor.org/rfc/rfc8701>
189 pub fn new(suite: &'static dyn Hpke, placeholder_key: HpkePublicKey) -> Self {
190 Self {
191 suite,
192 placeholder_key,
193 }
194 }
195
196 /// Build a GREASE ECH extension based on the placeholder configuration.
197 ///
198 /// See <https://datatracker.ietf.org/doc/html/draft-ietf-tls-esni-18#name-grease-ech> for
199 /// more information.
200 pub(crate) fn grease_ext(
201 &self,
202 secure_random: &'static dyn SecureRandom,
203 inner_name: ServerName<'static>,
204 outer_hello: &ClientHelloPayload,
205 ) -> Result<EncryptedClientHello, Error> {
206 trace!("Preparing GREASE ECH extension");
207
208 // Pick a random config id.
209 let mut config_id: [u8; 1] = [0; 1];
210 secure_random.fill(&mut config_id[..])?;
211
212 let suite = self.suite.suite();
213
214 // Construct a dummy ECH state - we don't have a real ECH config from a server since
215 // this is for GREASE.
216 let mut grease_state = EchState::new(
217 &EchConfig {
218 config: EchConfigPayload::V18(EchConfigContents {
219 key_config: HpkeKeyConfig {
220 config_id: config_id[0],
221 kem_id: HpkeKem::DHKEM_P256_HKDF_SHA256,
222 public_key: PayloadU16::new(self.placeholder_key.0.clone()),
223 symmetric_cipher_suites: vec![suite.sym],
224 },
225 maximum_name_length: 0,
226 public_name: DnsName::try_from("filler").unwrap(),
227 extensions: Vec::default(),
228 }),
229 suite: self.suite,
230 },
231 inner_name,
232 false,
233 secure_random,
234 false, // Does not matter if we enable/disable SNI here. Inner hello is not used.
235 )?;
236
237 // Construct an inner hello using the outer hello - this allows us to know the size of
238 // dummy payload we should use for the GREASE extension.
239 let encoded_inner_hello = grease_state.encode_inner_hello(outer_hello, None, &None);
240
241 // Generate a payload of random data equivalent in length to a real inner hello.
242 let payload_len = encoded_inner_hello.len()
243 + suite
244 .sym
245 .aead_id
246 .tag_len()
247 // Safety: we have confirmed the AEAD is supported when building the config. All
248 // supported AEADs have a tag length.
249 .unwrap();
250 let mut payload = vec![0; payload_len];
251 secure_random.fill(&mut payload)?;
252
253 // Return the GREASE extension.
254 Ok(EncryptedClientHello::Outer(EncryptedClientHelloOuter {
255 cipher_suite: suite.sym,
256 config_id: config_id[0],
257 enc: PayloadU16::new(grease_state.enc.0),
258 payload: PayloadU16::new(payload),
259 }))
260 }
261}
262
263/// An enum representing ECH offer status.
264#[derive(Debug, Clone, Copy, Eq, PartialEq)]
265pub enum EchStatus {
266 /// ECH was not offered - it is a normal TLS handshake.
267 NotOffered,
268 /// GREASE ECH was sent. This is not considered offering ECH.
269 Grease,
270 /// ECH was offered but we do not yet know whether the offer was accepted or rejected.
271 Offered,
272 /// ECH was offered and the server accepted.
273 Accepted,
274 /// ECH was offered and the server rejected.
275 Rejected,
276}
277
278/// Contextual data for a TLS client handshake that has offered encrypted client hello (ECH).
279pub(crate) struct EchState {
280 // The public DNS name from the ECH configuration we've chosen - this is included as the SNI
281 // value for the "outer" client hello. It can only be a DnsName, not an IP address.
282 pub(crate) outer_name: DnsName<'static>,
283 // If we're resuming in the inner hello, this is the early key schedule to use for encrypting
284 // early data if the ECH offer is accepted.
285 pub(crate) early_data_key_schedule: Option<KeyScheduleEarly>,
286 // A random value we use for the inner hello.
287 pub(crate) inner_hello_random: Random,
288 // A transcript buffer maintained for the inner hello. Once ECH is confirmed we switch to
289 // using this transcript for the handshake.
290 pub(crate) inner_hello_transcript: HandshakeHashBuffer,
291 // A source of secure random data.
292 secure_random: &'static dyn SecureRandom,
293 // An HPKE sealer context that can be used for encrypting ECH data.
294 sender: Box<dyn HpkeSealer>,
295 // The ID of the ECH configuration we've chosen - this is included in the outer ECH extension.
296 config_id: u8,
297 // The private server name we'll use for the inner protected hello.
298 inner_name: ServerName<'static>,
299 // The advertised maximum name length from the ECH configuration we've chosen - this is used
300 // for padding calculations.
301 maximum_name_length: u8,
302 // A supported symmetric cipher suite from the ECH configuration we've chosen - this is
303 // included in the outer ECH extension.
304 cipher_suite: HpkeSymmetricCipherSuite,
305 // A secret encapsulated to the public key of the remote server. This is included in the
306 // outer ECH extension for non-retry outer hello messages.
307 enc: EncapsulatedSecret,
308 // Whether the inner client hello should contain a server name indication (SNI) extension.
309 enable_sni: bool,
310 // The extensions sent in the inner hello.
311 sent_extensions: Vec<ExtensionType>,
312}
313
314impl EchState {
315 pub(crate) fn new(
316 config: &EchConfig,
317 inner_name: ServerName<'static>,
318 client_auth_enabled: bool,
319 secure_random: &'static dyn SecureRandom,
320 enable_sni: bool,
321 ) -> Result<Self, Error> {
322 let EchConfigPayload::V18(config_contents) = &config.config else {
323 // the public EchConfig::new() constructor ensures we only have supported
324 // configurations.
325 unreachable!("ECH config version mismatch");
326 };
327 let key_config = &config_contents.key_config;
328
329 // Encapsulate a secret for the server's public key, and set up a sender context
330 // we can use to seal messages.
331 let (enc, sender) = config.suite.setup_sealer(
332 &config.hpke_info(),
333 &HpkePublicKey(key_config.public_key.0.clone()),
334 )?;
335
336 // Start a new transcript buffer for the inner hello.
337 let mut inner_hello_transcript = HandshakeHashBuffer::new();
338 if client_auth_enabled {
339 inner_hello_transcript.set_client_auth_enabled();
340 }
341
342 Ok(Self {
343 secure_random,
344 sender,
345 config_id: key_config.config_id,
346 inner_name,
347 outer_name: config_contents.public_name.clone(),
348 maximum_name_length: config_contents.maximum_name_length,
349 cipher_suite: config.suite.suite().sym,
350 enc,
351 inner_hello_random: Random::new(secure_random)?,
352 inner_hello_transcript,
353 early_data_key_schedule: None,
354 enable_sni,
355 sent_extensions: Vec::new(),
356 })
357 }
358
359 /// Construct a ClientHelloPayload offering ECH.
360 ///
361 /// An outer hello, with a protected inner hello for the `inner_name` will be returned, and the
362 /// ECH context will be updated to reflect the inner hello that was offered.
363 ///
364 /// If `retry_req` is `Some`, then the outer hello will be constructed for a hello retry request.
365 ///
366 /// If `resuming` is `Some`, then the inner hello will be constructed for a resumption handshake.
367 pub(crate) fn ech_hello(
368 &mut self,
369 mut outer_hello: ClientHelloPayload,
370 retry_req: Option<&HelloRetryRequest>,
371 resuming: &Option<Retrieved<&persist::Tls13ClientSessionValue>>,
372 ) -> Result<ClientHelloPayload, Error> {
373 trace!(
374 "Preparing ECH offer {}",
375 if retry_req.is_some() { "for retry" } else { "" }
376 );
377
378 // Construct the encoded inner hello and update the transcript.
379 let encoded_inner_hello = self.encode_inner_hello(&outer_hello, retry_req, resuming);
380
381 // Complete the ClientHelloOuterAAD with an ech extension, the payload should be a placeholder
382 // of size L, all zeroes. L == length of encrypting encoded client hello inner w/ the selected
383 // HPKE AEAD. (sum of plaintext + tag length, typically).
384 let payload_len = encoded_inner_hello.len()
385 + self
386 .cipher_suite
387 .aead_id
388 .tag_len()
389 // Safety: we've already verified this AEAD is supported when loading the config
390 // that was used to create the ECH context. All supported AEADs have a tag length.
391 .unwrap();
392
393 // Outer hello's created in response to a hello retry request omit the enc value.
394 let enc = match retry_req.is_some() {
395 true => Vec::default(),
396 false => self.enc.0.clone(),
397 };
398
399 fn outer_hello_ext(ctx: &EchState, enc: Vec<u8>, payload: Vec<u8>) -> EncryptedClientHello {
400 EncryptedClientHello::Outer(EncryptedClientHelloOuter {
401 cipher_suite: ctx.cipher_suite,
402 config_id: ctx.config_id,
403 enc: PayloadU16::new(enc),
404 payload: PayloadU16::new(payload),
405 })
406 }
407
408 // The outer handshake is not permitted to resume a session. If we're resuming in the
409 // inner handshake we remove the PSK extension from the outer hello, replacing it
410 // with a GREASE PSK to implement the "ClientHello Malleability Mitigation" mentioned
411 // in 10.12.3.
412 if let Some(ClientExtension::PresharedKey(psk_offer)) = outer_hello.extensions.last_mut() {
413 self.grease_psk(psk_offer)?;
414 }
415
416 // To compute the encoded AAD we add a placeholder extension with an empty payload.
417 outer_hello
418 .extensions
419 .push(ClientExtension::EncryptedClientHello(outer_hello_ext(
420 self,
421 enc.clone(),
422 vec![0; payload_len],
423 )));
424
425 // Next we compute the proper extension payload.
426 let payload = self
427 .sender
428 .seal(&outer_hello.get_encoding(), &encoded_inner_hello)?;
429
430 // And then we replace the placeholder extension with the real one.
431 outer_hello.extensions.pop();
432 outer_hello
433 .extensions
434 .push(ClientExtension::EncryptedClientHello(outer_hello_ext(
435 self, enc, payload,
436 )));
437
438 Ok(outer_hello)
439 }
440
441 /// Confirm whether an ECH offer was accepted based on examining the server hello.
442 pub(crate) fn confirm_acceptance(
443 self,
444 ks: &mut KeyScheduleHandshakeStart,
445 server_hello: &ServerHelloPayload,
446 hash: &'static dyn Hash,
447 ) -> Result<Option<EchAccepted>, Error> {
448 // Start the inner transcript hash now that we know the hash algorithm to use.
449 let inner_transcript = self
450 .inner_hello_transcript
451 .start_hash(hash);
452
453 // Fork the transcript that we've started with the inner hello to use for a confirmation step.
454 // We need to preserve the original inner_transcript to use if this confirmation succeeds.
455 let mut confirmation_transcript = inner_transcript.clone();
456
457 // Add the server hello confirmation - this differs from the standard server hello encoding.
458 confirmation_transcript.add_message(&Self::server_hello_conf(server_hello));
459
460 // Derive a confirmation secret from the inner hello random and the confirmation transcript.
461 let derived = ks.server_ech_confirmation_secret(
462 self.inner_hello_random.0.as_ref(),
463 confirmation_transcript.current_hash(),
464 );
465
466 // Check that first 8 digits of the derived secret match the last 8 digits of the original
467 // server random. This match signals that the server accepted the ECH offer.
468 // Indexing safety: Random is [0; 32] by construction.
469
470 match ConstantTimeEq::ct_eq(derived.as_ref(), server_hello.random.0[24..].as_ref()).into() {
471 true => {
472 trace!("ECH accepted by server");
473 Ok(Some(EchAccepted {
474 transcript: inner_transcript,
475 random: self.inner_hello_random,
476 sent_extensions: self.sent_extensions,
477 }))
478 }
479 false => {
480 trace!("ECH rejected by server");
481 Ok(None)
482 }
483 }
484 }
485
486 pub(crate) fn confirm_hrr_acceptance(
487 &self,
488 hrr: &HelloRetryRequest,
489 cs: &Tls13CipherSuite,
490 common: &mut CommonState,
491 ) -> Result<bool, Error> {
492 // The client checks for the "encrypted_client_hello" extension.
493 let ech_conf = match hrr.ech() {
494 // If none is found, the server has implicitly rejected ECH.
495 None => return Ok(false),
496 // Otherwise, if it has a length other than 8, the client aborts the
497 // handshake with a "decode_error" alert.
498 Some(ech_conf) if ech_conf.len() != 8 => {
499 return Err({
500 common.send_fatal_alert(
501 AlertDescription::DecodeError,
502 PeerMisbehaved::IllegalHelloRetryRequestWithInvalidEch,
503 )
504 });
505 }
506 Some(ech_conf) => ech_conf,
507 };
508
509 // Otherwise the client computes hrr_accept_confirmation as described in Section
510 // 7.2.1
511 let confirmation_transcript = self.inner_hello_transcript.clone();
512 let mut confirmation_transcript =
513 confirmation_transcript.start_hash(cs.common.hash_provider);
514 confirmation_transcript.rollup_for_hrr();
515 confirmation_transcript.add_message(&Self::hello_retry_request_conf(hrr));
516
517 let derived = server_ech_hrr_confirmation_secret(
518 cs.hkdf_provider,
519 &self.inner_hello_random.0,
520 confirmation_transcript.current_hash(),
521 );
522
523 match ConstantTimeEq::ct_eq(derived.as_ref(), ech_conf).into() {
524 true => {
525 trace!("ECH accepted by server in hello retry request");
526 Ok(true)
527 }
528 false => {
529 trace!("ECH rejected by server in hello retry request");
530 Ok(false)
531 }
532 }
533 }
534
535 /// Update the ECH context inner hello transcript based on a received hello retry request message.
536 ///
537 /// This will start the in-progress transcript using the given `hash`, convert it into an HRR
538 /// buffer, and then add the hello retry message `m`.
539 pub(crate) fn transcript_hrr_update(&mut self, hash: &'static dyn Hash, m: &Message<'_>) {
540 trace!("Updating ECH inner transcript for HRR");
541
542 let inner_transcript = self
543 .inner_hello_transcript
544 .clone()
545 .start_hash(hash);
546
547 let mut inner_transcript_buffer = inner_transcript.into_hrr_buffer();
548 inner_transcript_buffer.add_message(m);
549 self.inner_hello_transcript = inner_transcript_buffer;
550 }
551
552 // 5.1 "Encoding the ClientHelloInner"
553 fn encode_inner_hello(
554 &mut self,
555 outer_hello: &ClientHelloPayload,
556 retryreq: Option<&HelloRetryRequest>,
557 resuming: &Option<Retrieved<&persist::Tls13ClientSessionValue>>,
558 ) -> Vec<u8> {
559 // Start building an inner hello using the outer_hello as a template.
560 let mut inner_hello = ClientHelloPayload {
561 // Some information is copied over as-is.
562 client_version: outer_hello.client_version,
563 session_id: outer_hello.session_id,
564 compression_methods: outer_hello.compression_methods.clone(),
565
566 // We will build up the included extensions ourselves.
567 extensions: vec![],
568
569 // Set the inner hello random to the one we generated when creating the ECH state.
570 // We hold on to the inner_hello_random in the ECH state to use later for confirming
571 // whether ECH was accepted or not.
572 random: self.inner_hello_random,
573
574 // We remove the empty renegotiation info SCSV from the outer hello's ciphersuite.
575 // Similar to the TLS 1.2 specific extensions we will filter out, this is seen as a
576 // TLS 1.2 only feature by bogo.
577 cipher_suites: outer_hello
578 .cipher_suites
579 .iter()
580 .filter(|cs| **cs != TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
581 .cloned()
582 .collect(),
583 };
584
585 // The inner hello will always have an inner variant of the ECH extension added.
586 // See Section 6.1 rule 4.
587 inner_hello
588 .extensions
589 .push(ClientExtension::EncryptedClientHello(
590 EncryptedClientHello::Inner,
591 ));
592
593 let inner_sni = match &self.inner_name {
594 // The inner hello only gets a SNI value if enable_sni is true and the inner name
595 // is a domain name (not an IP address).
596 ServerName::DnsName(dns_name) if self.enable_sni => Some(dns_name),
597 _ => None,
598 };
599
600 // Now we consider each of the outer hello's extensions - we can either:
601 // 1. Omit the extension if it isn't appropriate (e.g. is a TLS 1.2 extension).
602 // 2. Add the extension to the inner hello as-is.
603 // 3. Compress the extension, by collecting it into a list of to-be-compressed
604 // extensions we'll handle separately.
605 let mut compressed_exts = Vec::with_capacity(outer_hello.extensions.len());
606 let mut compressed_ext_types = Vec::with_capacity(outer_hello.extensions.len());
607 for ext in &outer_hello.extensions {
608 // Some outer hello extensions are only useful in the context where a TLS 1.3
609 // connection allows TLS 1.2. This isn't the case for ECH so we skip adding them
610 // to the inner hello.
611 if matches!(
612 ext.ext_type(),
613 ExtensionType::ExtendedMasterSecret
614 | ExtensionType::SessionTicket
615 | ExtensionType::ECPointFormats
616 ) {
617 continue;
618 }
619
620 if ext.ext_type() == ExtensionType::ServerName {
621 // We may want to replace the outer hello SNI with our own inner hello specific SNI.
622 if let Some(sni_value) = inner_sni {
623 inner_hello
624 .extensions
625 .push(ClientExtension::ServerName(ServerNamePayload::from(
626 sni_value,
627 )));
628 }
629 // We don't want to add, or compress, the SNI from the outer hello.
630 continue;
631 }
632
633 // Compressed extensions need to be put aside to include in one contiguous block.
634 // Uncompressed extensions get added directly to the inner hello.
635 if ext.ext_type().ech_compress() {
636 compressed_exts.push(ext.clone());
637 compressed_ext_types.push(ext.ext_type());
638 } else {
639 inner_hello.extensions.push(ext.clone());
640 }
641 }
642
643 // We've added all the uncompressed extensions. Now we need to add the contiguous
644 // block of to-be-compressed extensions. Where we do this depends on whether the
645 // last uncompressed extension is a PSK for resumption. In this case we must
646 // add the to-be-compressed extensions _before_ the PSK.
647 let compressed_exts_index =
648 if let Some(ClientExtension::PresharedKey(_)) = inner_hello.extensions.last() {
649 inner_hello.extensions.len() - 1
650 } else {
651 inner_hello.extensions.len()
652 };
653 inner_hello.extensions.splice(
654 compressed_exts_index..compressed_exts_index,
655 compressed_exts,
656 );
657
658 // Note which extensions we're sending in the inner hello. This may differ from
659 // the outer hello (e.g. the inner hello may omit SNI while the outer hello will
660 // always have the ECH cover name in SNI).
661 self.sent_extensions = inner_hello
662 .extensions
663 .iter()
664 .map(|ext| ext.ext_type())
665 .collect();
666
667 // If we're resuming, we need to update the PSK binder in the inner hello.
668 if let Some(resuming) = resuming.as_ref() {
669 let mut chp = HandshakeMessagePayload(HandshakePayload::ClientHello(inner_hello));
670
671 // Retain the early key schedule we get from processing the binder.
672 self.early_data_key_schedule = Some(tls13::fill_in_psk_binder(
673 resuming,
674 &self.inner_hello_transcript,
675 &mut chp,
676 ));
677
678 // fill_in_psk_binder works on an owned HandshakeMessagePayload, so we need to
679 // extract our inner hello back out of it to retain ownership.
680 inner_hello = match chp.0 {
681 HandshakePayload::ClientHello(chp) => chp,
682 // Safety: we construct the HMP above and know its type unconditionally.
683 _ => unreachable!(),
684 };
685 }
686
687 trace!("ECH Inner Hello: {inner_hello:#?}");
688
689 // Encode the inner hello according to the rules required for ECH. This differs
690 // from the standard encoding in several ways. Notably this is where we will
691 // replace the block of contiguous to-be-compressed extensions with a marker.
692 let mut encoded_hello = inner_hello.ech_inner_encoding(compressed_ext_types);
693
694 // Calculate padding
695 // max_name_len = L
696 let max_name_len = self.maximum_name_length;
697 let max_name_len = if max_name_len > 0 { max_name_len } else { 255 };
698
699 let padding_len = match &self.inner_name {
700 ServerName::DnsName(name) => {
701 // name.len() = D
702 // max(0, L - D)
703 core::cmp::max(
704 0,
705 max_name_len.saturating_sub(name.as_ref().len() as u8) as usize,
706 )
707 }
708 _ => {
709 // L + 9
710 // "This is the length of a "server_name" extension with an L-byte name."
711 // We widen to usize here to avoid overflowing u8 + u8.
712 max_name_len as usize + 9
713 }
714 };
715
716 // Let L be the length of the EncodedClientHelloInner with all the padding computed so far
717 // Let N = 31 - ((L - 1) % 32) and add N bytes of padding.
718 let padding_len = 31 - ((encoded_hello.len() + padding_len - 1) % 32);
719 encoded_hello.extend(vec![0; padding_len]);
720
721 // Construct the inner hello message that will be used for the transcript.
722 let inner_hello_msg = Message {
723 version: match retryreq {
724 // <https://datatracker.ietf.org/doc/html/rfc8446#section-5.1>:
725 // "This value MUST be set to 0x0303 for all records generated
726 // by a TLS 1.3 implementation ..."
727 Some(_) => ProtocolVersion::TLSv1_2,
728 // "... other than an initial ClientHello (i.e., one not
729 // generated after a HelloRetryRequest), where it MAY also be
730 // 0x0301 for compatibility purposes"
731 //
732 // (retryreq == None means we're in the "initial ClientHello" case)
733 None => ProtocolVersion::TLSv1_0,
734 },
735 payload: MessagePayload::handshake(HandshakeMessagePayload(
736 HandshakePayload::ClientHello(inner_hello),
737 )),
738 };
739
740 // Update the inner transcript buffer with the inner hello message.
741 self.inner_hello_transcript
742 .add_message(&inner_hello_msg);
743
744 encoded_hello
745 }
746
747 // See https://datatracker.ietf.org/doc/html/draft-ietf-tls-esni-18#name-grease-psk
748 fn grease_psk(&self, psk_offer: &mut PresharedKeyOffer) -> Result<(), Error> {
749 for ident in psk_offer.identities.iter_mut() {
750 // "For each PSK identity advertised in the ClientHelloInner, the
751 // client generates a random PSK identity with the same length."
752 self.secure_random
753 .fill(&mut ident.identity.0)?;
754 // "It also generates a random, 32-bit, unsigned integer to use as
755 // the obfuscated_ticket_age."
756 let mut ticket_age = [0_u8; 4];
757 self.secure_random
758 .fill(&mut ticket_age)?;
759 ident.obfuscated_ticket_age = u32::from_be_bytes(ticket_age);
760 }
761
762 // "Likewise, for each inner PSK binder, the client generates a random string
763 // of the same length."
764 psk_offer.binders = psk_offer
765 .binders
766 .iter()
767 .map(|old_binder| {
768 // We can't access the wrapped binder PresharedKeyBinder's PayloadU8 mutably,
769 // so we construct new PresharedKeyBinder's from scratch with the same length.
770 let mut new_binder = vec![0; old_binder.as_ref().len()];
771 self.secure_random
772 .fill(&mut new_binder)?;
773 Ok::<PresharedKeyBinder, Error>(PresharedKeyBinder::from(new_binder))
774 })
775 .collect::<Result<_, _>>()?;
776 Ok(())
777 }
778
779 fn server_hello_conf(server_hello: &ServerHelloPayload) -> Message<'_> {
780 Self::ech_conf_message(HandshakeMessagePayload(HandshakePayload::ServerHello(
781 server_hello.clone(),
782 )))
783 }
784
785 fn hello_retry_request_conf(retry_req: &HelloRetryRequest) -> Message<'_> {
786 Self::ech_conf_message(HandshakeMessagePayload(
787 HandshakePayload::HelloRetryRequest(retry_req.clone()),
788 ))
789 }
790
791 fn ech_conf_message(hmp: HandshakeMessagePayload<'_>) -> Message<'_> {
792 let mut hmp_encoded = Vec::new();
793 hmp.payload_encode(&mut hmp_encoded, Encoding::EchConfirmation);
794 Message {
795 version: ProtocolVersion::TLSv1_3,
796 payload: MessagePayload::Handshake {
797 encoded: Payload::new(hmp_encoded),
798 parsed: hmp,
799 },
800 }
801 }
802}
803
804/// Returned from EchState::check_acceptance when the server has accepted the ECH offer.
805///
806/// Holds the state required to continue the handshake with the inner hello from the ECH offer.
807pub(crate) struct EchAccepted {
808 pub(crate) transcript: HandshakeHash,
809 pub(crate) random: Random,
810 pub(crate) sent_extensions: Vec<ExtensionType>,
811}
812
813pub(crate) fn fatal_alert_required(
814 retry_configs: Option<Vec<EchConfigPayload>>,
815 common: &mut CommonState,
816) -> Error {
817 common.send_fatal_alert(
818 AlertDescription::EncryptedClientHelloRequired,
819 PeerIncompatible::ServerRejectedEncryptedClientHello(retry_configs),
820 )
821}