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