Skip to main content

rustls/client/
ech.rs

1use alloc::boxed::Box;
2use alloc::vec;
3use alloc::vec::Vec;
4use core::iter;
5
6use pki_types::{DnsName, EchConfigListBytes, FipsStatus, ServerName};
7use subtle::ConstantTimeEq;
8
9use super::config::ClientConfig;
10use super::{Retrieved, Tls13Session, tls13};
11use crate::common_state::Protocol;
12use crate::crypto::cipher::{EncodableVersion, Payload};
13use crate::crypto::hash::Hash;
14use crate::crypto::hpke::{
15    EncapsulatedSecret, Hpke, HpkeKem, HpkePublicKey, HpkeSealer, HpkeSuite,
16    HpkeSymmetricCipherSuite,
17};
18use crate::crypto::{CipherSuite, SecureRandom};
19use crate::enums::ProtocolVersion;
20use crate::error::{EncryptedClientHelloError, Error, PeerMisbehaved, RejectedEch};
21use crate::hash_hs::{HandshakeHash, HandshakeHashBuffer};
22use crate::msgs::{
23    ClientExtensions, ClientHelloPayload, Codec, EchConfigContents, EchConfigPayload, Encoding,
24    EncryptedClientHello, EncryptedClientHelloOuter, ExtensionType, HandshakeAlignedProof,
25    HandshakeMessagePayload, HandshakePayload, HelloRetryRequest, HpkeKeyConfig, Message,
26    MessagePayload, PresharedKeyBinder, PresharedKeyIdentity, PresharedKeyOffer, Random,
27    ServerHelloPayload, ServerNamePayload, SizedPayload,
28};
29use crate::tls13::Tls13CipherSuite;
30use crate::tls13::key_schedule::{
31    KeyScheduleEarlyClient, KeyScheduleHandshakeStart, server_ech_hrr_confirmation_secret,
32};
33use crate::tracing::{debug, trace, warn};
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 the FIPS status of the HPKE suite that will be used.
52    pub fn fips(&self) -> FipsStatus {
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_bytes(&ech_config_list).map_err(|_| {
105            Error::InvalidEncryptedClientHello(EncryptedClientHelloError::InvalidConfigList)
106        })?;
107
108        Self::new_for_configs(ech_configs, hpke_suites)
109    }
110
111    /// Build an EchConfig for retrying ECH using a retry config from a server's previous rejection
112    ///
113    /// Returns an error if the server provided no retry configurations in [`RejectedEch`], or if
114    /// none of the retry configurations are compatible with the supported `hpke_suites`.
115    pub fn for_retry(
116        rejection: RejectedEch,
117        hpke_suites: &[&'static dyn Hpke],
118    ) -> Result<Self, Error> {
119        let Some(configs) = rejection.retry_configs else {
120            return Err(EncryptedClientHelloError::NoCompatibleConfig.into());
121        };
122
123        Self::new_for_configs(configs, hpke_suites)
124    }
125
126    pub(super) fn state(
127        &self,
128        server_name: ServerName<'static>,
129        config: &ClientConfig,
130    ) -> Result<EchState, Error> {
131        EchState::new(
132            self,
133            server_name,
134            !config
135                .resolver()
136                .supported_certificate_types()
137                .is_empty(),
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/rfc9849#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        for (i, config) in ech_configs.iter().enumerate() {
159            let contents = match config {
160                EchConfigPayload::V18(contents) => contents,
161                EchConfigPayload::Unknown { version, .. } => {
162                    warn!("ECH config {} has unsupported version {:?}", i + 1, version);
163                    continue; // Unsupported version.
164                }
165            };
166
167            if contents.has_unknown_mandatory_extension() || contents.has_duplicate_extension() {
168                warn!("ECH config has duplicate, or unknown mandatory extensions: {contents:?}",);
169                continue; // Unsupported, or malformed extensions.
170            }
171
172            let key_config = &contents.key_config;
173            for cipher_suite in &key_config.symmetric_cipher_suites {
174                if cipher_suite.aead_id.tag_len().is_none() {
175                    continue; // Unsupported EXPORT_ONLY AEAD cipher suite.
176                }
177
178                let suite = HpkeSuite {
179                    kem: key_config.kem_id,
180                    sym: *cipher_suite,
181                };
182                if let Some(hpke) = hpke_suites
183                    .iter()
184                    .find(|hpke| hpke.suite() == suite)
185                {
186                    debug!(
187                        "selected ECH config ID {:?} suite {:?} public_name {:?}",
188                        key_config.config_id, suite, contents.public_name
189                    );
190                    return Ok(Self {
191                        config: config.clone(),
192                        suite: *hpke,
193                    });
194                }
195            }
196        }
197
198        Err(EncryptedClientHelloError::NoCompatibleConfig.into())
199    }
200}
201
202/// Configuration for GREASE Encrypted Client Hello.
203#[derive(Clone, Debug)]
204pub struct EchGreaseConfig {
205    pub(crate) suite: &'static dyn Hpke,
206    pub(crate) placeholder_key: HpkePublicKey,
207}
208
209impl EchGreaseConfig {
210    /// Construct a GREASE ECH configuration.
211    ///
212    /// This configuration is used when the client wishes to offer ECH to prevent ossification,
213    /// but doesn't have a real ECH configuration to use for the remote server. In this case
214    /// a placeholder or "GREASE"[^0] extension is used.
215    ///
216    /// Returns an error if the HPKE provider does not support the given suite.
217    ///
218    /// [^0]: <https://www.rfc-editor.org/rfc/rfc8701>
219    pub fn new(suite: &'static dyn Hpke, placeholder_key: HpkePublicKey) -> Self {
220        Self {
221            suite,
222            placeholder_key,
223        }
224    }
225
226    /// Build a GREASE ECH extension based on the placeholder configuration.
227    ///
228    /// See <https://datatracker.ietf.org/doc/html/rfc9849#name-grease-ech> for
229    /// more information.
230    pub(crate) fn grease_ext(
231        &self,
232        secure_random: &'static dyn SecureRandom,
233        inner_name: ServerName<'static>,
234        outer_hello: &ClientHelloPayload,
235    ) -> Result<EncryptedClientHello, Error> {
236        trace!("Preparing GREASE ECH extension");
237
238        // Pick a random config id.
239        let mut config_id: [u8; 1] = [0; 1];
240        secure_random.fill(&mut config_id[..])?;
241
242        let suite = self.suite.suite();
243
244        // Construct a dummy ECH state - we don't have a real ECH config from a server since
245        // this is for GREASE.
246        let mut grease_state = EchState::new(
247            &EchConfig {
248                config: EchConfigPayload::V18(EchConfigContents {
249                    key_config: HpkeKeyConfig {
250                        config_id: config_id[0],
251                        kem_id: HpkeKem::DHKEM_P256_HKDF_SHA256,
252                        public_key: SizedPayload::from(self.placeholder_key.0.clone()),
253                        symmetric_cipher_suites: vec![suite.sym],
254                    },
255                    maximum_name_length: 0,
256                    public_name: DnsName::try_from("filler").unwrap(),
257                    extensions: Vec::default(),
258                }),
259                suite: self.suite,
260            },
261            inner_name,
262            false,
263            secure_random,
264            false, // Does not matter if we enable/disable SNI here. Inner hello is not used.
265        )?;
266
267        // Construct an inner hello using the outer hello - this allows us to know the size of
268        // dummy payload we should use for the GREASE extension.
269        let encoded_inner_hello = grease_state.encode_inner_hello(outer_hello, None, None)?;
270
271        // Generate a payload of random data equivalent in length to a real inner hello.
272        let payload_len = encoded_inner_hello.len()
273            + suite
274                .sym
275                .aead_id
276                .tag_len()
277                // Safety: we have confirmed the AEAD is supported when building the config. All
278                //  supported AEADs have a tag length.
279                .unwrap();
280        let mut payload = vec![0; payload_len];
281        secure_random.fill(&mut payload)?;
282
283        // Return the GREASE extension.
284        Ok(EncryptedClientHello::Outer(EncryptedClientHelloOuter {
285            cipher_suite: suite.sym,
286            config_id: config_id[0],
287            enc: SizedPayload::from(Payload::new(grease_state.enc.0)),
288            payload: SizedPayload::from(Payload::new(payload)),
289        }))
290    }
291}
292
293/// An enum representing ECH offer status.
294#[non_exhaustive]
295#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
296pub enum EchStatus {
297    /// ECH was not offered - it is a normal TLS handshake.
298    #[default]
299    NotOffered,
300    /// GREASE ECH was sent. This is not considered offering ECH.
301    Grease,
302    /// ECH was offered but we do not yet know whether the offer was accepted or rejected.
303    Offered,
304    /// ECH was offered and the server accepted.
305    Accepted,
306    /// ECH was offered and the server rejected.
307    Rejected,
308}
309
310/// Contextual data for a TLS client handshake that has offered encrypted client hello (ECH).
311pub(crate) struct EchState {
312    // The public DNS name from the ECH configuration we've chosen - this is included as the SNI
313    // value for the "outer" client hello. It can only be a DnsName, not an IP address.
314    pub(crate) outer_name: DnsName<'static>,
315    // If we're resuming in the inner hello, this is the early key schedule to use for encrypting
316    // early data if the ECH offer is accepted.
317    pub(crate) early_data_key_schedule: Option<KeyScheduleEarlyClient>,
318    // A random value we use for the inner hello.
319    pub(crate) inner_hello_random: Random,
320    // A transcript buffer maintained for the inner hello. Once ECH is confirmed we switch to
321    // using this transcript for the handshake.
322    pub(crate) inner_hello_transcript: HandshakeHashBuffer,
323    // A source of secure random data.
324    secure_random: &'static dyn SecureRandom,
325    // An HPKE sealer context that can be used for encrypting ECH data.
326    sender: Box<dyn HpkeSealer>,
327    // The ID of the ECH configuration we've chosen - this is included in the outer ECH extension.
328    config_id: u8,
329    // The private server name we'll use for the inner protected hello.
330    inner_name: ServerName<'static>,
331    // The advertised maximum name length from the ECH configuration we've chosen - this is used
332    // for padding calculations.
333    maximum_name_length: u8,
334    // A supported symmetric cipher suite from the ECH configuration we've chosen - this is
335    // included in the outer ECH extension.
336    cipher_suite: HpkeSymmetricCipherSuite,
337    // A secret encapsulated to the public key of the remote server. This is included in the
338    // outer ECH extension for non-retry outer hello messages.
339    enc: EncapsulatedSecret,
340    // Whether the inner client hello should contain a server name indication (SNI) extension.
341    enable_sni: bool,
342    // The extensions sent in the inner hello.
343    sent_extensions: Vec<ExtensionType>,
344    // The GREASE PSK identities offered in the first outer hello, if any. A retry hello
345    // re-offers the same identities.
346    grease_psk_identities: Option<Vec<PresharedKeyIdentity>>,
347    // Whether a hello retry request accepted our ECH offer, if we received one. RFC 9849
348    // section 6.1.4 makes that decision final.
349    accepted_by_hello_retry_request: Option<bool>,
350}
351
352impl EchState {
353    pub(crate) fn new(
354        config: &EchConfig,
355        inner_name: ServerName<'static>,
356        client_auth_enabled: bool,
357        secure_random: &'static dyn SecureRandom,
358        enable_sni: bool,
359    ) -> Result<Self, Error> {
360        let EchConfigPayload::V18(config_contents) = &config.config else {
361            // the public EchConfig::new() constructor ensures we only have supported
362            // configurations.
363            unreachable!("ECH config version mismatch");
364        };
365        let key_config = &config_contents.key_config;
366
367        // Encapsulate a secret for the server's public key, and set up a sender context
368        // we can use to seal messages.
369        let (enc, sender) = config.suite.setup_sealer(
370            &config.hpke_info(),
371            &HpkePublicKey(key_config.public_key.to_vec()),
372        )?;
373
374        // Start a new transcript buffer for the inner hello.
375        let mut inner_hello_transcript = HandshakeHashBuffer::new();
376        if client_auth_enabled {
377            inner_hello_transcript.set_client_auth_enabled();
378        }
379
380        Ok(Self {
381            outer_name: config_contents.public_name.clone(),
382            early_data_key_schedule: None,
383            inner_hello_random: Random::new(secure_random)?,
384            inner_hello_transcript,
385            secure_random,
386            sender,
387            config_id: key_config.config_id,
388            inner_name,
389            maximum_name_length: config_contents.maximum_name_length,
390            cipher_suite: config.suite.suite().sym,
391            enc,
392            enable_sni,
393            sent_extensions: Vec::new(),
394            grease_psk_identities: None,
395            accepted_by_hello_retry_request: None,
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<&Tls13Session>>,
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: SizedPayload::from(Payload::new(enc)),
444                payload: SizedPayload::from(Payload::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: &KeyScheduleHandshakeStart,
475        server_hello: &ServerHelloPayload,
476        server_hello_encoded: &Payload<'_>,
477        hash: &'static dyn Hash,
478        server_name: &mut ServerName<'static>,
479    ) -> Result<Option<EchAccepted>, Error> {
480        // After a rejecting hello retry request the handshake continues with the outer hello
481        // without consulting the server hello, see RFC 9849 section 6.1.6.
482        if self.accepted_by_hello_retry_request == Some(false) {
483            trace!("ECH rejected by server in hello retry request");
484            *server_name = self.outer_name.into();
485            return Ok(None);
486        }
487
488        // Start the inner transcript hash now that we know the hash algorithm to use.
489        let inner_transcript = self
490            .inner_hello_transcript
491            .start_hash(hash);
492
493        // Fork the transcript that we've started with the inner hello to use for a confirmation step.
494        // We need to preserve the original inner_transcript to use if this confirmation succeeds.
495        let mut confirmation_transcript = inner_transcript.clone();
496
497        // Add the server hello confirmation - this is computed by altering the received
498        // encoding rather than reencoding it.
499        confirmation_transcript
500            .add_message(&Self::server_hello_conf(server_hello, server_hello_encoded));
501
502        // Derive a confirmation secret from the inner hello random and the confirmation transcript.
503        let derived = ks.server_ech_confirmation_secret(
504            self.inner_hello_random.0.as_ref(),
505            confirmation_transcript.current_hash(),
506        );
507
508        // Check that first 8 digits of the derived secret match the last 8 digits of the original
509        // server random. This match signals that the server accepted the ECH offer.
510        // Indexing safety: Random is [0; 32] by construction.
511
512        match ConstantTimeEq::ct_eq(derived.as_ref(), server_hello.random.0[24..].as_ref()).into() {
513            true => {
514                trace!("ECH accepted by server");
515                Ok(Some(EchAccepted {
516                    transcript: inner_transcript,
517                    random: self.inner_hello_random,
518                    sent_extensions: self.sent_extensions,
519                }))
520            }
521            // An accepting hello retry request requires an "illegal_parameter" alert here
522            // -- <https://www.rfc-editor.org/info/rfc9849/#section-6.1.5>
523            false if self.accepted_by_hello_retry_request == Some(true) => {
524                Err(PeerMisbehaved::EchAcceptanceVariedAfterRetry.into())
525            }
526            false => {
527                trace!("ECH rejected by server");
528
529                // "If the server rejects ECH, the client proceeds with the handshake, authenticating
530                // for ECHConfig.contents.public_name"
531                // -- <https://www.rfc-editor.org/info/rfc9849/#section-6.1.6>
532                *server_name = self.outer_name.into();
533
534                Ok(None)
535            }
536        }
537    }
538
539    pub(crate) fn confirm_hrr_acceptance(
540        &mut self,
541        hrr: &HelloRetryRequest,
542        cs: &Tls13CipherSuite,
543    ) -> Result<bool, Error> {
544        // The client checks for the "encrypted_client_hello" extension.
545        let ech_conf = match &hrr.encrypted_client_hello {
546            // If none is found, the server has implicitly rejected ECH.
547            None => {
548                self.accepted_by_hello_retry_request = Some(false);
549                return Ok(false);
550            }
551            // Otherwise, if it has a length other than 8, the client aborts the
552            // handshake with a "decode_error" alert.
553            Some(ech_conf) if ech_conf.bytes().len() != 8 => {
554                return Err(PeerMisbehaved::IllegalHelloRetryRequestWithInvalidEch.into());
555            }
556            Some(ech_conf) => ech_conf,
557        };
558
559        // Otherwise the client computes hrr_accept_confirmation as described in Section
560        // 7.2.1
561        let confirmation_transcript = self.inner_hello_transcript.clone();
562        let mut confirmation_transcript =
563            confirmation_transcript.start_hash(cs.common.hash_provider);
564        confirmation_transcript.rollup_for_hrr();
565        confirmation_transcript.add_message(&Self::hello_retry_request_conf(hrr));
566
567        let derived = server_ech_hrr_confirmation_secret(
568            cs.hkdf_provider,
569            &self.inner_hello_random.0,
570            confirmation_transcript.current_hash(),
571        );
572
573        let accepted = match ConstantTimeEq::ct_eq(derived.as_ref(), ech_conf.bytes()).into() {
574            true => {
575                trace!("ECH accepted by server in hello retry request");
576                true
577            }
578            false => {
579                trace!("ECH rejected by server in hello retry request");
580                false
581            }
582        };
583        self.accepted_by_hello_retry_request = Some(accepted);
584        Ok(accepted)
585    }
586
587    /// Update the ECH context inner hello transcript based on a received hello retry request message.
588    ///
589    /// This will start the in-progress transcript using the given `hash`, convert it into an HRR
590    /// buffer, and then add the hello retry message `m`.
591    pub(crate) fn transcript_hrr_update(
592        &mut self,
593        hash: &'static dyn Hash,
594        m: &Message<'_>,
595        proof: &HandshakeAlignedProof,
596    ) {
597        trace!("Updating ECH inner transcript for HRR");
598
599        let inner_transcript = self
600            .inner_hello_transcript
601            .clone()
602            .start_hash(hash);
603
604        let mut inner_transcript_buffer = inner_transcript.into_hrr_buffer(proof);
605        inner_transcript_buffer.add_message(m);
606        self.inner_hello_transcript = inner_transcript_buffer;
607    }
608
609    // See https://datatracker.ietf.org/doc/html/rfc9849#name-grease-psk
610    pub(super) fn grease_psk(&mut self, psk_offer: &mut PresharedKeyOffer) -> Result<(), Error> {
611        match &self.grease_psk_identities {
612            // This is a retry hello: re-offer the identities and ages from the first hello,
613            // as a genuine PSK offer would. Only the binders are regenerated below; a fresh
614            // GREASE PSK here would "stick out" to an attacker triggering a retry.
615            Some(identities) => psk_offer.identities = identities.clone(),
616            None => {
617                for ident in psk_offer.identities.iter_mut() {
618                    // "For each PSK identity advertised in the ClientHelloInner, the
619                    // client generates a random PSK identity with the same length."
620                    let Some(identity) = ident.identity.as_mut() else {
621                        unreachable!();
622                    };
623                    self.secure_random.fill(identity)?;
624
625                    // "It also generates a random, 32-bit, unsigned integer to use as
626                    // the obfuscated_ticket_age."
627                    let mut ticket_age = [0_u8; 4];
628                    self.secure_random
629                        .fill(&mut ticket_age)?;
630                    ident.obfuscated_ticket_age = u32::from_be_bytes(ticket_age);
631                }
632
633                self.grease_psk_identities = Some(psk_offer.identities.clone());
634            }
635        }
636
637        // "Likewise, for each inner PSK binder, the client generates a random string
638        // of the same length."
639        psk_offer.binders = psk_offer
640            .binders
641            .iter()
642            .map(|old_binder| {
643                // We can't access the wrapped binder PresharedKeyBinder's PayloadU8 mutably,
644                // so we construct new PresharedKeyBinder's from scratch with the same length.
645                let mut new_binder = vec![0; old_binder.as_ref().len()];
646                self.secure_random
647                    .fill(&mut new_binder)?;
648                Ok::<PresharedKeyBinder, Error>(PresharedKeyBinder::from(new_binder))
649            })
650            .collect::<Result<_, _>>()?;
651        Ok(())
652    }
653
654    // 5.1 "Encoding the ClientHelloInner"
655    fn encode_inner_hello(
656        &mut self,
657        outer_hello: &ClientHelloPayload,
658        retryreq: Option<&HelloRetryRequest>,
659        resuming: Option<&Retrieved<&Tls13Session>>,
660    ) -> Result<Vec<u8>, Error> {
661        // Start building an inner hello using the outer_hello as a template.
662        let mut inner_hello = ClientHelloPayload {
663            // Some information is copied over as-is.
664            client_version: outer_hello.client_version,
665
666            // Set the inner hello random to the one we generated when creating the ECH state.
667            // We hold on to the inner_hello_random in the ECH state to use later for confirming
668            // whether ECH was accepted or not.
669            random: self.inner_hello_random,
670            session_id: outer_hello.session_id,
671
672            // We remove the empty renegotiation info SCSV from the outer hello's ciphersuite.
673            // Similar to the TLS 1.2 specific extensions we will filter out, this is seen as a
674            // TLS 1.2 only feature by bogo.
675            cipher_suites: outer_hello
676                .cipher_suites
677                .iter()
678                .filter(|cs| **cs != CipherSuite::TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
679                .copied()
680                .collect(),
681            compression_methods: outer_hello.compression_methods.clone(),
682
683            // We will build up the included extensions ourselves.
684            extensions: Box::new(ClientExtensions::default()),
685        };
686
687        inner_hello.order_seed = outer_hello.order_seed;
688
689        // The inner hello will always have an inner variant of the ECH extension added.
690        // See Section 6.1 rule 4.
691        inner_hello.encrypted_client_hello = Some(EncryptedClientHello::Inner);
692
693        let inner_sni = match &self.inner_name {
694            // The inner hello only gets a SNI value if enable_sni is true and the inner name
695            // is a domain name (not an IP address).
696            ServerName::DnsName(dns_name) if self.enable_sni => Some(dns_name),
697            _ => None,
698        };
699
700        // Now we consider each of the outer hello's extensions - we can either:
701        // 1. Omit the extension if it isn't appropriate (e.g. is a TLS 1.2 extension).
702        // 2. Add the extension to the inner hello as-is.
703        // 3. Compress the extension, by collecting it into a list of to-be-compressed
704        //    extensions we'll handle separately.
705        let outer_extensions = outer_hello.used_extensions_in_encoding_order();
706        let mut compressed_exts = Vec::with_capacity(outer_extensions.len());
707        for ext in outer_extensions {
708            // Some outer hello extensions are only useful in the context where a TLS 1.3
709            // connection allows TLS 1.2. This isn't the case for ECH so we skip adding them
710            // to the inner hello.
711            if matches!(
712                ext,
713                ExtensionType::ExtendedMainSecret
714                    | ExtensionType::SessionTicket
715                    | ExtensionType::ECPointFormats
716            ) {
717                continue;
718            }
719
720            if ext == ExtensionType::ServerName {
721                // We may want to replace the outer hello SNI with our own inner hello specific SNI.
722                if let Some(sni_value) = inner_sni {
723                    inner_hello.server_name = Some(ServerNamePayload::from(sni_value));
724                }
725                // We don't want to add, or compress, the SNI from the outer hello.
726                continue;
727            }
728
729            // Compressed extensions need to be put aside to include in one contiguous block.
730            // Uncompressed extensions get added directly to the inner hello.
731            if ext.ech_compress() {
732                compressed_exts.push(ext);
733            }
734
735            inner_hello.clone_one(outer_hello, ext);
736        }
737
738        // We've added all the uncompressed extensions. Now we need to add the contiguous
739        // block of to-be-compressed extensions.
740        inner_hello.contiguous_extensions = compressed_exts.clone();
741
742        // Note which extensions we're sending in the inner hello. This may differ from
743        // the outer hello (e.g. the inner hello may omit SNI while the outer hello will
744        // always have the ECH cover name in SNI).
745        self.sent_extensions = inner_hello.collect_used();
746
747        // If we're resuming, we need to update the PSK binder in the inner hello.
748        if let Some(resuming) = resuming.as_ref() {
749            let mut chp = HandshakeMessagePayload(HandshakePayload::ClientHello(inner_hello));
750
751            let key_schedule =
752                KeyScheduleEarlyClient::new(resuming.suite, resuming.secret.bytes())?;
753            tls13::fill_in_psk_binder(&key_schedule, &self.inner_hello_transcript, &mut chp);
754            self.early_data_key_schedule = Some(key_schedule);
755
756            // fill_in_psk_binder works on an owned HandshakeMessagePayload, so we need to
757            // extract our inner hello back out of it to retain ownership.
758            inner_hello = match chp.0 {
759                HandshakePayload::ClientHello(chp) => chp,
760                // Safety: we construct the HMP above and know its type unconditionally.
761                _ => unreachable!(),
762            };
763        }
764
765        trace!("ECH Inner Hello: {inner_hello:#?}");
766
767        // Encode the inner hello according to the rules required for ECH. This differs
768        // from the standard encoding in several ways. Notably this is where we will
769        // replace the block of contiguous to-be-compressed extensions with a marker.
770        let mut encoded_hello = inner_hello.ech_inner_encoding(compressed_exts);
771
772        // Calculate padding
773        // max_name_len = L
774        let max_name_len = usize::from(self.maximum_name_length);
775        let max_name_len = if max_name_len > 0 { max_name_len } else { 255 };
776
777        let name_padding_len = match &inner_hello.server_name {
778            Some(ServerNamePayload::SingleDnsName(name)) => {
779                // name.len() = D
780                // max(0, L - D)
781                Ord::max(0, max_name_len.saturating_sub(name.as_ref().len()))
782            }
783            // L + 9
784            // "This is the length of a "server_name" extension with an L-byte name."
785            _ => max_name_len + 9,
786        };
787        encoded_hello.extend(iter::repeat_n(0, name_padding_len));
788
789        // Let L be the length of the EncodedClientHelloInner with all the padding computed so far
790        // Let N = 31 - ((L - 1) % 32) and add N bytes of padding.
791        let padding_len = 31 - ((encoded_hello.len() - 1) % 32);
792        encoded_hello.extend(iter::repeat_n(0, padding_len));
793
794        // Construct the inner hello message that will be used for the transcript.
795        let inner_hello_msg = Message {
796            version: match retryreq {
797                // <https://datatracker.ietf.org/doc/html/rfc9846#section-5.1>:
798                // "This value MUST be set to 0x0303 for all records generated
799                //  by a TLS 1.3 implementation ..."
800                Some(_) => EncodableVersion::Legacy(ProtocolVersion::TLSv1_2),
801                // "... other than an initial ClientHello (i.e., one not
802                // generated after a HelloRetryRequest), where it MAY also be
803                // 0x0301 for compatibility purposes"
804                //
805                // (retryreq == None means we're in the "initial ClientHello" case)
806                None => EncodableVersion::InitialClientHello(Protocol::Tcp),
807            },
808            payload: MessagePayload::handshake(HandshakeMessagePayload(
809                HandshakePayload::ClientHello(inner_hello),
810            )),
811        };
812
813        // Update the inner transcript buffer with the inner hello message.
814        self.inner_hello_transcript
815            .add_message(&inner_hello_msg);
816
817        Ok(encoded_hello)
818    }
819
820    fn server_hello_conf(
821        server_hello: &ServerHelloPayload,
822        server_hello_encoded: &Payload<'_>,
823    ) -> Message<'static> {
824        // The confirmation is computed over the server hello, which has had
825        // its `random` field altered to zero the final 8 bytes.
826        //
827        // nb. we don't require that we can round-trip a `ServerHelloPayload`, to
828        // allow for efficiency in its in-memory representation.  That means
829        // we operate here on the received encoding, as the confirmation needs
830        // to be computed on that.
831        let mut encoded = server_hello_encoded.clone().into_vec();
832        encoded[SERVER_HELLO_ECH_CONFIRMATION_SPAN].fill(0x00);
833
834        Message {
835            version: EncodableVersion::Legacy(ProtocolVersion::TLSv1_3),
836            payload: MessagePayload::Handshake {
837                encoded: Payload::Owned(encoded),
838                parsed: HandshakeMessagePayload(HandshakePayload::ServerHello(
839                    server_hello.clone(),
840                )),
841            },
842        }
843    }
844
845    fn hello_retry_request_conf(retry_req: &HelloRetryRequest) -> Message<'_> {
846        Self::ech_conf_message(HandshakeMessagePayload(
847            HandshakePayload::HelloRetryRequest(retry_req.clone()),
848        ))
849    }
850
851    fn ech_conf_message(hmp: HandshakeMessagePayload<'_>) -> Message<'_> {
852        let mut hmp_encoded = Vec::new();
853        hmp.payload_encode(&mut hmp_encoded, Encoding::EchConfirmation);
854        Message {
855            version: EncodableVersion::Legacy(ProtocolVersion::TLSv1_3),
856            payload: MessagePayload::Handshake {
857                encoded: Payload::new(hmp_encoded),
858                parsed: hmp,
859            },
860        }
861    }
862}
863
864/// The last eight bytes of the ServerHello's random, taken from a Handshake message containing it.
865///
866/// This has:
867/// - a HandshakeType (1 byte),
868/// - an exterior length (3 bytes),
869/// - the legacy_version (2 bytes), and
870/// - the balance of the random field (24 bytes).
871const SERVER_HELLO_ECH_CONFIRMATION_SPAN: core::ops::Range<usize> =
872    (1 + 3 + 2 + 24)..(1 + 3 + 2 + 32);
873
874/// Returned from EchState::confirm_acceptance when the server has accepted the ECH offer.
875///
876/// Holds the state required to continue the handshake with the inner hello from the ECH offer.
877pub(crate) struct EchAccepted {
878    pub(crate) transcript: HandshakeHash,
879    pub(crate) random: Random,
880    pub(crate) sent_extensions: Vec<ExtensionType>,
881}
882
883#[cfg(test)]
884mod tests {
885    use core::sync::atomic::{AtomicU8, Ordering};
886    use core::time::Duration;
887    use std::string::String;
888
889    use pki_types::{CertificateDer, SubjectPublicKeyInfoDer, UnixTime};
890
891    use super::*;
892    use crate::client::{
893        ClientSessionKey, ClientSessionMemoryCache, ClientSessionStore, Resumption,
894        Tls13ClientSessionInput, VerifiedIdentity,
895    };
896    use crate::crypto::cipher::Record;
897    use crate::crypto::hpke::{HpkeAead, HpkeKdf};
898    use crate::crypto::kx::SharedSecret;
899    use crate::crypto::{CipherSuite, GetRandomFailed, Identity, TEST_PROVIDER, tls13_only};
900    use crate::msgs::{
901        Compression, Deframer, HelloRetryRequestExtensions, NewSessionTicketPayloadTls13, Random,
902        Reader, ServerExtensions, SessionId, SupportedProtocolVersions,
903    };
904    use crate::quic::Side;
905    use crate::sync::Arc;
906    use crate::tls13::Tls13ProtocolSuite;
907    use crate::tls13::key_schedule::KeySchedulePreHandshake;
908    use crate::{RootCertStore, VecInput};
909
910    #[test]
911    fn server_hello_conf_alters_server_hello_random() {
912        let server_hello = ServerHelloPayload {
913            legacy_version: ProtocolVersion::TLSv1_2,
914            random: Random([0xffu8; 32]),
915            session_id: SessionId::empty(),
916            cipher_suite: CipherSuite::TLS13_AES_256_GCM_SHA384,
917            compression_method: Compression::Null,
918            extensions: Box::new(ServerExtensions::default()),
919        };
920        let message = Message {
921            version: EncodableVersion::Legacy(ProtocolVersion::TLSv1_3),
922            payload: MessagePayload::handshake(HandshakeMessagePayload(
923                HandshakePayload::ServerHello(server_hello.clone()),
924            )),
925        };
926        let Message {
927            payload:
928                MessagePayload::Handshake {
929                    encoded: server_hello_encoded_before,
930                    ..
931                },
932            ..
933        } = &message
934        else {
935            unreachable!("ServerHello is a handshake message");
936        };
937
938        let message = EchState::server_hello_conf(&server_hello, server_hello_encoded_before);
939
940        let Message {
941            payload:
942                MessagePayload::Handshake {
943                    encoded: server_hello_encoded_after,
944                    ..
945                },
946            ..
947        } = &message
948        else {
949            unreachable!("ServerHello is a handshake message");
950        };
951
952        assert_eq!(
953            std::format!("{server_hello_encoded_before:x?}"),
954            "020000280303ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001302000000",
955            "beforehand eight bytes at end of Random should be 0xff here ^^^^^^^^^^^^^^^^            "
956        );
957        assert_eq!(
958            std::format!("{server_hello_encoded_after:x?}"),
959            "020000280303ffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000001302000000",
960            "                          afterwards those bytes are zeroed ^^^^^^^^^^^^^^^^            "
961        );
962    }
963
964    #[test]
965    fn inner_client_hello_length_conceals_inner_name_length() {
966        let base_inner_len = inner_hello_encoding_for_name(dns_name_of_len(1), true)
967            .unwrap()
968            .len();
969        assert!(
970            base_inner_len % 32 == 0,
971            "inner hello length must be 32-byte padded"
972        );
973        assert!(
974            base_inner_len >= 256,
975            "inner hello must include inner name and its padding"
976        );
977
978        for inner_name_len in 1..251 {
979            assert_eq!(
980                inner_hello_encoding_for_name(dns_name_of_len(inner_name_len), true)
981                    .unwrap()
982                    .len(),
983                base_inner_len,
984                "all inner hello lengths must be invariant wrt inner name length"
985            );
986        }
987    }
988
989    #[test]
990    fn inner_client_hello_length_does_not_leak_length_of_omitted_inner_name() {
991        let base_inner_len = inner_hello_encoding_for_name(dns_name_of_len(1), false)
992            .unwrap()
993            .len();
994        assert!(
995            base_inner_len % 32 == 0,
996            "inner hello length must be 32-byte padded"
997        );
998        assert!(
999            base_inner_len >= 256,
1000            "inner hello must include maximum_name_length bytes of padding"
1001        );
1002
1003        for inner_name_len in 1..251 {
1004            assert_eq!(
1005                inner_hello_encoding_for_name(dns_name_of_len(inner_name_len), false)
1006                    .unwrap()
1007                    .len(),
1008                base_inner_len,
1009                "all inner hello lengths must be invariant wrt inner name length"
1010            );
1011        }
1012    }
1013
1014    #[test]
1015    fn ech_rejected_by_hello_retry_request_conceals_inner_psk() {
1016        let mut roots = RootCertStore::empty();
1017        roots
1018            .add(CertificateDer::from_slice(include_bytes!(
1019                "../../../test-ca/rsa-2048/ca.der"
1020            )))
1021            .unwrap();
1022
1023        // `TEST_PROVIDER`'s fixed-fill `SecureRandom` would mask a regression here: a
1024        // fresh GREASE PSK generated for the retry would repeat the first hello's
1025        // identity by happenstance. A counter makes consecutive fills distinct.
1026        let mut provider = tls13_only(TEST_PROVIDER.clone());
1027        provider.secure_random = &CountingRandom;
1028
1029        let config = ClientConfig::builder(Arc::new(provider))
1030            .with_ech(EchMode::Enable(EchConfig {
1031                config: EchConfigPayload::V18(EchConfigContents {
1032                    key_config: HpkeKeyConfig {
1033                        config_id: 0,
1034                        kem_id: MockHpke::SUITE.kem,
1035                        public_key: vec![0; 32].into(),
1036                        symmetric_cipher_suites: vec![MockHpke::SUITE.sym],
1037                    },
1038                    maximum_name_length: 255,
1039                    public_name: DnsName::try_from("public.example.com").unwrap(),
1040                    extensions: vec![],
1041                }),
1042                suite: &MockHpke,
1043            }))
1044            .with_root_certificates(roots)
1045            .with_no_client_auth()
1046            .unwrap();
1047        let store = Arc::new(ClientSessionMemoryCache::new(256));
1048        let config = Arc::new(ClientConfig {
1049            resumption: Resumption::store(store.clone()),
1050            ..config
1051        });
1052
1053        // cache a ticket for the concealed inner name
1054        let server_name = ServerName::try_from("inner.example.com").unwrap();
1055        store.insert_tls13_ticket(
1056            ClientSessionKey {
1057                config_hash: config.config_hash(),
1058                server_name: server_name.clone(),
1059            },
1060            Tls13Session::new(
1061                &NewSessionTicketPayloadTls13::new(
1062                    Duration::from_secs(1800),
1063                    0x1234_5678,
1064                    [0u8; 32],
1065                    TICKET.to_vec(),
1066                ),
1067                Tls13ClientSessionInput {
1068                    suite: Tls13ProtocolSuite::Tcp(TEST_PROVIDER.tls13_cipher_suites[0]),
1069                    peer_identity: VerifiedIdentity::assertion(Identity::RawPublicKey(
1070                        SubjectPublicKeyInfoDer::from(&b"spki"[..]),
1071                    )),
1072                    quic_params: None,
1073                },
1074                &[0x55; 32],
1075                UnixTime::now(),
1076            ),
1077        );
1078
1079        let mut first_flight = Vec::new();
1080        let mut conn = config
1081            .connect(server_name)
1082            .build(&mut first_flight)
1083            .unwrap();
1084
1085        // the ticket belongs to the concealed inner name, so the outer hello offers
1086        // a GREASE PSK in its place
1087        let first = client_hello_in(&first_flight);
1088        assert_ne!(psk_identity(&first), TICKET);
1089
1090        // a HelloRetryRequest without `encrypted_client_hello` rejects our ECH offer
1091        let hrr = Message {
1092            version: EncodableVersion::Legacy(ProtocolVersion::TLSv1_2),
1093            payload: MessagePayload::handshake(HandshakeMessagePayload(
1094                HandshakePayload::HelloRetryRequest(HelloRetryRequest {
1095                    legacy_version: ProtocolVersion::TLSv1_2,
1096                    session_id: first.session_id,
1097                    cipher_suite: first.cipher_suites[0],
1098                    extensions: HelloRetryRequestExtensions {
1099                        cookie: Some(SizedPayload::from(vec![1, 2, 3, 4])),
1100                        supported_versions: Some(ProtocolVersion::TLSv1_3),
1101                        ..HelloRetryRequestExtensions::default()
1102                    },
1103                }),
1104            )),
1105        };
1106        let mut input = VecInput::default();
1107        input
1108            .read(&mut hrr.into_wire_bytes().as_slice())
1109            .unwrap();
1110        let mut retry_flight = Vec::new();
1111        conn.read_tls(&mut input, &mut retry_flight)
1112            .handle_all(&mut Vec::new())
1113            .unwrap();
1114
1115        // we continue with a second outer hello: it must conceal the ticket too, and
1116        // must re-offer the first hello's GREASE identity as a genuine PSK offer would
1117        let second = client_hello_in(&retry_flight);
1118        assert_ne!(psk_identity(&second), TICKET);
1119        assert_eq!(psk_identity(&second), psk_identity(&first));
1120
1121        fn client_hello_in(bytes: &[u8]) -> ClientHelloPayload {
1122            let mut reader = Reader::new(bytes);
1123            while reader.any_left() {
1124                let record = Record::<Payload<'_>>::read(&mut reader)
1125                    .unwrap()
1126                    .into_owned();
1127                if let Ok(Message {
1128                    payload:
1129                        MessagePayload::Handshake {
1130                            parsed: HandshakeMessagePayload(HandshakePayload::ClientHello(ch)),
1131                            ..
1132                        },
1133                    ..
1134                }) = Message::try_from(&record)
1135                {
1136                    return ch;
1137                }
1138            }
1139            panic!("no ClientHello written");
1140        }
1141
1142        fn psk_identity(hello: &ClientHelloPayload) -> &[u8] {
1143            hello
1144                .preshared_key_offer
1145                .as_ref()
1146                .unwrap()
1147                .identities[0]
1148                .identity
1149                .bytes()
1150        }
1151
1152        const TICKET: &[u8] = b"inner name resumption ticket";
1153
1154        #[derive(Debug)]
1155        struct CountingRandom;
1156
1157        impl SecureRandom for CountingRandom {
1158            fn fill(&self, bytes: &mut [u8]) -> Result<(), GetRandomFailed> {
1159                static COUNTER: AtomicU8 = AtomicU8::new(0);
1160                for byte in bytes.iter_mut() {
1161                    *byte = COUNTER.fetch_add(1, Ordering::Relaxed);
1162                }
1163                Ok(())
1164            }
1165        }
1166    }
1167
1168    #[test]
1169    fn ech_rejection_in_server_hello_after_acceptance_in_hello_retry_request() {
1170        let suite = TEST_PROVIDER.tls13_cipher_suites[0];
1171        let hash = suite.common.hash_provider;
1172        let proof = Deframer::default().aligned().unwrap();
1173        let mut state = ech_state();
1174
1175        // the server accepts our offer in its hello retry request...
1176        state
1177            .ech_hello(outer_hello(), None, None)
1178            .unwrap();
1179        let hrr = accepting_hello_retry_request(&state, suite);
1180        assert!(
1181            state
1182                .confirm_hrr_acceptance(&hrr, suite)
1183                .unwrap()
1184        );
1185        state.transcript_hrr_update(hash, &hrr_message(&hrr), &proof);
1186        state
1187            .ech_hello(outer_hello(), Some(&hrr), None)
1188            .unwrap();
1189
1190        // ...but its server hello does not confirm that acceptance
1191        let server_hello = server_hello(suite);
1192        let mut server_name = inner_name();
1193        assert_eq!(
1194            state
1195                .confirm_acceptance(
1196                    &handshake_key_schedule(suite),
1197                    &server_hello,
1198                    &encode(&server_hello),
1199                    hash,
1200                    &mut server_name,
1201                )
1202                .err(),
1203            Some(PeerMisbehaved::EchAcceptanceVariedAfterRetry.into())
1204        );
1205    }
1206
1207    #[test]
1208    fn ech_acceptance_in_server_hello_after_rejection_in_hello_retry_request() {
1209        let suite = TEST_PROVIDER.tls13_cipher_suites[0];
1210        let hash = suite.common.hash_provider;
1211        let proof = Deframer::default().aligned().unwrap();
1212        let key_schedule = handshake_key_schedule(suite);
1213
1214        // without a hello retry request, a confirming server hello accepts ECH
1215        let mut state = ech_state();
1216        state
1217            .ech_hello(outer_hello(), None, None)
1218            .unwrap();
1219        let server_hello = confirming_server_hello(&state, &key_schedule, suite);
1220        let mut server_name = inner_name();
1221        assert!(
1222            state
1223                .confirm_acceptance(
1224                    &key_schedule,
1225                    &server_hello,
1226                    &encode(&server_hello),
1227                    hash,
1228                    &mut server_name,
1229                )
1230                .unwrap()
1231                .is_some()
1232        );
1233        assert_eq!(server_name, inner_name());
1234
1235        // but after a rejecting hello retry request, a confirming server hello cannot revive it
1236        let mut state = ech_state();
1237        state
1238            .ech_hello(outer_hello(), None, None)
1239            .unwrap();
1240        let hrr = hello_retry_request(suite, None);
1241        assert!(
1242            !state
1243                .confirm_hrr_acceptance(&hrr, suite)
1244                .unwrap()
1245        );
1246        state.transcript_hrr_update(hash, &hrr_message(&hrr), &proof);
1247        let server_hello = confirming_server_hello(&state, &key_schedule, suite);
1248        let mut server_name = inner_name();
1249        assert!(
1250            state
1251                .confirm_acceptance(
1252                    &key_schedule,
1253                    &server_hello,
1254                    &encode(&server_hello),
1255                    hash,
1256                    &mut server_name,
1257                )
1258                .unwrap()
1259                .is_none()
1260        );
1261        assert_eq!(server_name, ServerName::from(public_name()));
1262    }
1263
1264    fn ech_state() -> EchState {
1265        let config = EchConfig {
1266            config: EchConfigPayload::V18(EchConfigContents {
1267                key_config: HpkeKeyConfig {
1268                    config_id: 0,
1269                    kem_id: MockHpke::SUITE.kem,
1270                    public_key: vec![0; 32].into(),
1271                    symmetric_cipher_suites: vec![MockHpke::SUITE.sym],
1272                },
1273                maximum_name_length: 255,
1274                public_name: public_name(),
1275                extensions: vec![],
1276            }),
1277            suite: &MockHpke,
1278        };
1279
1280        EchState::new(
1281            &config,
1282            inner_name(),
1283            false,
1284            TEST_PROVIDER.secure_random,
1285            true,
1286        )
1287        .unwrap()
1288    }
1289
1290    fn inner_name() -> ServerName<'static> {
1291        ServerName::try_from("inner.example.com").unwrap()
1292    }
1293
1294    fn public_name() -> DnsName<'static> {
1295        DnsName::try_from("public.example.com").unwrap()
1296    }
1297
1298    fn outer_hello() -> ClientHelloPayload {
1299        ClientHelloPayload {
1300            client_version: ProtocolVersion::TLSv1_2,
1301            random: Random([0u8; 32]),
1302            session_id: SessionId::empty(),
1303            cipher_suites: vec![
1304                TEST_PROVIDER.tls13_cipher_suites[0]
1305                    .common
1306                    .suite,
1307            ],
1308            compression_methods: vec![Compression::Null],
1309            extensions: Box::new(ClientExtensions {
1310                server_name: Some(ServerNamePayload::from(&public_name())),
1311                supported_versions: Some(SupportedProtocolVersions {
1312                    tls13: true,
1313                    tls12: false,
1314                }),
1315                ..Default::default()
1316            }),
1317        }
1318    }
1319
1320    fn hello_retry_request(
1321        suite: &'static Tls13CipherSuite,
1322        encrypted_client_hello: Option<Payload<'static>>,
1323    ) -> HelloRetryRequest {
1324        HelloRetryRequest {
1325            legacy_version: ProtocolVersion::TLSv1_2,
1326            session_id: SessionId::empty(),
1327            cipher_suite: suite.common.suite,
1328            extensions: HelloRetryRequestExtensions {
1329                cookie: Some(SizedPayload::from(vec![1, 2, 3, 4])),
1330                supported_versions: Some(ProtocolVersion::TLSv1_3),
1331                encrypted_client_hello,
1332                ..HelloRetryRequestExtensions::default()
1333            },
1334        }
1335    }
1336
1337    /// A hello retry request accepting the offer in `state`, see RFC 9849 section 7.2.1.
1338    fn accepting_hello_retry_request(
1339        state: &EchState,
1340        suite: &'static Tls13CipherSuite,
1341    ) -> HelloRetryRequest {
1342        let mut hrr = hello_retry_request(suite, Some(Payload::new(vec![0u8; 8])));
1343        let mut transcript = state
1344            .inner_hello_transcript
1345            .clone()
1346            .start_hash(suite.common.hash_provider);
1347        transcript.rollup_for_hrr();
1348        transcript.add_message(&EchState::hello_retry_request_conf(&hrr));
1349        let confirmation = server_ech_hrr_confirmation_secret(
1350            suite.hkdf_provider,
1351            &state.inner_hello_random.0,
1352            transcript.current_hash(),
1353        );
1354        hrr.encrypted_client_hello = Some(Payload::new(confirmation.to_vec()));
1355        hrr
1356    }
1357
1358    fn hrr_message(hrr: &HelloRetryRequest) -> Message<'static> {
1359        Message {
1360            version: EncodableVersion::Legacy(ProtocolVersion::TLSv1_2),
1361            payload: MessagePayload::handshake(HandshakeMessagePayload(
1362                HandshakePayload::HelloRetryRequest(hrr.clone()),
1363            )),
1364        }
1365    }
1366
1367    fn server_hello(suite: &'static Tls13CipherSuite) -> ServerHelloPayload {
1368        ServerHelloPayload {
1369            legacy_version: ProtocolVersion::TLSv1_2,
1370            random: Random([0x55u8; 32]),
1371            session_id: SessionId::empty(),
1372            cipher_suite: suite.common.suite,
1373            compression_method: Compression::Null,
1374            extensions: Box::new(ServerExtensions::default()),
1375        }
1376    }
1377
1378    /// A server hello accepting the offer in `state`, see RFC 9849 section 7.2.
1379    fn confirming_server_hello(
1380        state: &EchState,
1381        key_schedule: &KeyScheduleHandshakeStart,
1382        suite: &'static Tls13CipherSuite,
1383    ) -> ServerHelloPayload {
1384        let mut server_hello = server_hello(suite);
1385        let mut transcript = state
1386            .inner_hello_transcript
1387            .clone()
1388            .start_hash(suite.common.hash_provider);
1389        transcript.add_message(&EchState::server_hello_conf(
1390            &server_hello,
1391            &encode(&server_hello),
1392        ));
1393        let confirmation = key_schedule
1394            .server_ech_confirmation_secret(&state.inner_hello_random.0, transcript.current_hash());
1395        server_hello.random.0[24..].copy_from_slice(&confirmation);
1396        server_hello
1397    }
1398
1399    fn encode(server_hello: &ServerHelloPayload) -> Payload<'static> {
1400        Payload::new(
1401            HandshakeMessagePayload(HandshakePayload::ServerHello(server_hello.clone()))
1402                .get_encoding(),
1403        )
1404    }
1405
1406    fn handshake_key_schedule(suite: &'static Tls13CipherSuite) -> KeyScheduleHandshakeStart {
1407        KeySchedulePreHandshake::new(Side::Client, Tls13ProtocolSuite::Tcp(suite))
1408            .unwrap()
1409            .into_handshake(SharedSecret::from(&[0u8; 32][..]))
1410    }
1411
1412    fn inner_hello_encoding_for_name(
1413        name: DnsName<'static>,
1414        enable_sni: bool,
1415    ) -> Result<Vec<u8>, Error> {
1416        let config = EchConfig {
1417            config: EchConfigPayload::V18(EchConfigContents {
1418                key_config: HpkeKeyConfig {
1419                    config_id: 0,
1420                    kem_id: MockHpke::SUITE.kem,
1421                    public_key: vec![0; 32].into(),
1422                    symmetric_cipher_suites: vec![],
1423                },
1424                maximum_name_length: 255,
1425                public_name: DnsName::try_from("public").unwrap(),
1426                extensions: vec![],
1427            }),
1428            suite: &MockHpke,
1429        };
1430
1431        EchState::new(
1432            &config,
1433            ServerName::from(name.clone()),
1434            false,
1435            TEST_PROVIDER.secure_random,
1436            enable_sni,
1437        )
1438        .unwrap()
1439        .encode_inner_hello(
1440            &ClientHelloPayload {
1441                client_version: ProtocolVersion::TLSv1_3,
1442                random: Random([0u8; 32]),
1443                session_id: SessionId::empty(),
1444                cipher_suites: vec![],
1445                compression_methods: vec![Compression::Null],
1446                extensions: Box::new(ClientExtensions {
1447                    server_name: Some(ServerNamePayload::from(&name)),
1448                    ..Default::default()
1449                }),
1450            },
1451            None,
1452            None,
1453        )
1454    }
1455
1456    fn dns_name_of_len(mut len: usize) -> DnsName<'static> {
1457        let mut s = String::new();
1458        let labels = len.div_ceil(63);
1459        for _ in 0..labels {
1460            let chars = Ord::min(len, 63);
1461            len -= chars;
1462            for _ in 0..chars {
1463                s.push('a');
1464            }
1465            if len != 0 {
1466                s.push('.');
1467            }
1468        }
1469        DnsName::try_from(s).unwrap()
1470    }
1471
1472    #[derive(Debug)]
1473    struct MockHpke;
1474
1475    impl MockHpke {
1476        const SUITE: HpkeSuite = HpkeSuite {
1477            kem: HpkeKem::DHKEM_P256_HKDF_SHA256,
1478            sym: HpkeSymmetricCipherSuite {
1479                kdf_id: HpkeKdf::HKDF_SHA256,
1480                aead_id: HpkeAead::AES_128_GCM,
1481            },
1482        };
1483    }
1484
1485    impl Hpke for MockHpke {
1486        #[cfg_attr(coverage_nightly, coverage(off))]
1487        fn seal(
1488            &self,
1489            _info: &[u8],
1490            _aad: &[u8],
1491            _plaintext: &[u8],
1492            _pub_key: &HpkePublicKey,
1493        ) -> Result<(EncapsulatedSecret, Vec<u8>), Error> {
1494            todo!()
1495        }
1496
1497        fn setup_sealer(
1498            &self,
1499            _info: &[u8],
1500            _pub_key: &HpkePublicKey,
1501        ) -> Result<(EncapsulatedSecret, Box<dyn HpkeSealer + 'static>), Error> {
1502            Ok((EncapsulatedSecret(vec![]), Box::new(MockHpkeSealer)))
1503        }
1504
1505        #[cfg_attr(coverage_nightly, coverage(off))]
1506        fn open(
1507            &self,
1508            _enc: &EncapsulatedSecret,
1509            _info: &[u8],
1510            _aad: &[u8],
1511            _ciphertext: &[u8],
1512            _secret_key: &crate::crypto::hpke::HpkePrivateKey,
1513        ) -> Result<Vec<u8>, Error> {
1514            todo!()
1515        }
1516
1517        #[cfg_attr(coverage_nightly, coverage(off))]
1518        fn setup_opener(
1519            &self,
1520            _enc: &EncapsulatedSecret,
1521            _info: &[u8],
1522            _secret_key: &crate::crypto::hpke::HpkePrivateKey,
1523        ) -> Result<Box<dyn crate::crypto::hpke::HpkeOpener + 'static>, Error> {
1524            todo!()
1525        }
1526
1527        #[cfg_attr(coverage_nightly, coverage(off))]
1528        fn generate_key_pair(
1529            &self,
1530        ) -> Result<(HpkePublicKey, crate::crypto::hpke::HpkePrivateKey), Error> {
1531            todo!()
1532        }
1533
1534        fn suite(&self) -> HpkeSuite {
1535            Self::SUITE
1536        }
1537    }
1538
1539    #[derive(Debug)]
1540    struct MockHpkeSealer;
1541
1542    impl HpkeSealer for MockHpkeSealer {
1543        fn seal(&mut self, _aad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, Error> {
1544            // ciphertext length as if sealed with the AEAD named in `MockHpke::SUITE`
1545            Ok(vec![0xff; plaintext.len() + 16])
1546        }
1547    }
1548}