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}
348
349impl EchState {
350    pub(crate) fn new(
351        config: &EchConfig,
352        inner_name: ServerName<'static>,
353        client_auth_enabled: bool,
354        secure_random: &'static dyn SecureRandom,
355        enable_sni: bool,
356    ) -> Result<Self, Error> {
357        let EchConfigPayload::V18(config_contents) = &config.config else {
358            // the public EchConfig::new() constructor ensures we only have supported
359            // configurations.
360            unreachable!("ECH config version mismatch");
361        };
362        let key_config = &config_contents.key_config;
363
364        // Encapsulate a secret for the server's public key, and set up a sender context
365        // we can use to seal messages.
366        let (enc, sender) = config.suite.setup_sealer(
367            &config.hpke_info(),
368            &HpkePublicKey(key_config.public_key.to_vec()),
369        )?;
370
371        // Start a new transcript buffer for the inner hello.
372        let mut inner_hello_transcript = HandshakeHashBuffer::new();
373        if client_auth_enabled {
374            inner_hello_transcript.set_client_auth_enabled();
375        }
376
377        Ok(Self {
378            outer_name: config_contents.public_name.clone(),
379            early_data_key_schedule: None,
380            inner_hello_random: Random::new(secure_random)?,
381            inner_hello_transcript,
382            secure_random,
383            sender,
384            config_id: key_config.config_id,
385            inner_name,
386            maximum_name_length: config_contents.maximum_name_length,
387            cipher_suite: config.suite.suite().sym,
388            enc,
389            enable_sni,
390            sent_extensions: Vec::new(),
391            grease_psk_identities: None,
392        })
393    }
394
395    /// Construct a ClientHelloPayload offering ECH.
396    ///
397    /// An outer hello, with a protected inner hello for the `inner_name` will be returned, and the
398    /// ECH context will be updated to reflect the inner hello that was offered.
399    ///
400    /// If `retry_req` is `Some`, then the outer hello will be constructed for a hello retry request.
401    ///
402    /// If `resuming` is `Some`, then the inner hello will be constructed for a resumption handshake.
403    pub(crate) fn ech_hello(
404        &mut self,
405        mut outer_hello: ClientHelloPayload,
406        retry_req: Option<&HelloRetryRequest>,
407        resuming: Option<&Retrieved<&Tls13Session>>,
408    ) -> Result<ClientHelloPayload, Error> {
409        trace!(
410            "Preparing ECH offer {}",
411            if retry_req.is_some() { "for retry" } else { "" }
412        );
413
414        // Construct the encoded inner hello and update the transcript.
415        let encoded_inner_hello = self.encode_inner_hello(&outer_hello, retry_req, resuming)?;
416
417        // Complete the ClientHelloOuterAAD with an ech extension, the payload should be a placeholder
418        // of size L, all zeroes. L == length of encrypting encoded client hello inner w/ the selected
419        // HPKE AEAD. (sum of plaintext + tag length, typically).
420        let payload_len = encoded_inner_hello.len()
421            + self
422                .cipher_suite
423                .aead_id
424                .tag_len()
425                // Safety: we've already verified this AEAD is supported when loading the config
426                // that was used to create the ECH context. All supported AEADs have a tag length.
427                .unwrap();
428
429        // Outer hello's created in response to a hello retry request omit the enc value.
430        let enc = match retry_req.is_some() {
431            true => Vec::default(),
432            false => self.enc.0.clone(),
433        };
434
435        fn outer_hello_ext(ctx: &EchState, enc: Vec<u8>, payload: Vec<u8>) -> EncryptedClientHello {
436            EncryptedClientHello::Outer(EncryptedClientHelloOuter {
437                cipher_suite: ctx.cipher_suite,
438                config_id: ctx.config_id,
439                enc: SizedPayload::from(Payload::new(enc)),
440                payload: SizedPayload::from(Payload::new(payload)),
441            })
442        }
443
444        // The outer handshake is not permitted to resume a session. If we're resuming in the
445        // inner handshake we remove the PSK extension from the outer hello, replacing it
446        // with a GREASE PSK to implement the "ClientHello Malleability Mitigation" mentioned
447        // in 10.12.3.
448        if let Some(psk_offer) = outer_hello.preshared_key_offer.as_mut() {
449            self.grease_psk(psk_offer)?;
450        }
451
452        // To compute the encoded AAD we add a placeholder extension with an empty payload.
453        outer_hello.encrypted_client_hello =
454            Some(outer_hello_ext(self, enc.clone(), vec![0; payload_len]));
455
456        // Next we compute the proper extension payload.
457        let payload = self
458            .sender
459            .seal(&outer_hello.get_encoding(), &encoded_inner_hello)?;
460
461        // And then we replace the placeholder extension with the real one.
462        outer_hello.encrypted_client_hello = Some(outer_hello_ext(self, enc, payload));
463
464        Ok(outer_hello)
465    }
466
467    /// Confirm whether an ECH offer was accepted based on examining the server hello.
468    pub(crate) fn confirm_acceptance(
469        self,
470        ks: &KeyScheduleHandshakeStart,
471        server_hello: &ServerHelloPayload,
472        server_hello_encoded: &Payload<'_>,
473        hash: &'static dyn Hash,
474        server_name: &mut ServerName<'static>,
475    ) -> Result<Option<EchAccepted>, Error> {
476        // Start the inner transcript hash now that we know the hash algorithm to use.
477        let inner_transcript = self
478            .inner_hello_transcript
479            .start_hash(hash);
480
481        // Fork the transcript that we've started with the inner hello to use for a confirmation step.
482        // We need to preserve the original inner_transcript to use if this confirmation succeeds.
483        let mut confirmation_transcript = inner_transcript.clone();
484
485        // Add the server hello confirmation - this is computed by altering the received
486        // encoding rather than reencoding it.
487        confirmation_transcript
488            .add_message(&Self::server_hello_conf(server_hello, server_hello_encoded));
489
490        // Derive a confirmation secret from the inner hello random and the confirmation transcript.
491        let derived = ks.server_ech_confirmation_secret(
492            self.inner_hello_random.0.as_ref(),
493            confirmation_transcript.current_hash(),
494        );
495
496        // Check that first 8 digits of the derived secret match the last 8 digits of the original
497        // server random. This match signals that the server accepted the ECH offer.
498        // Indexing safety: Random is [0; 32] by construction.
499
500        match ConstantTimeEq::ct_eq(derived.as_ref(), server_hello.random.0[24..].as_ref()).into() {
501            true => {
502                trace!("ECH accepted by server");
503                Ok(Some(EchAccepted {
504                    transcript: inner_transcript,
505                    random: self.inner_hello_random,
506                    sent_extensions: self.sent_extensions,
507                }))
508            }
509            false => {
510                trace!("ECH rejected by server");
511
512                // "If the server rejects ECH, the client proceeds with the handshake, authenticating
513                // for ECHConfig.contents.public_name"
514                // -- <https://www.rfc-editor.org/info/rfc9849/#section-6.1.6>
515                *server_name = self.outer_name.into();
516
517                Ok(None)
518            }
519        }
520    }
521
522    pub(crate) fn confirm_hrr_acceptance(
523        &self,
524        hrr: &HelloRetryRequest,
525        cs: &Tls13CipherSuite,
526    ) -> Result<bool, Error> {
527        // The client checks for the "encrypted_client_hello" extension.
528        let ech_conf = match &hrr.encrypted_client_hello {
529            // If none is found, the server has implicitly rejected ECH.
530            None => return Ok(false),
531            // Otherwise, if it has a length other than 8, the client aborts the
532            // handshake with a "decode_error" alert.
533            Some(ech_conf) if ech_conf.bytes().len() != 8 => {
534                return Err(PeerMisbehaved::IllegalHelloRetryRequestWithInvalidEch.into());
535            }
536            Some(ech_conf) => ech_conf,
537        };
538
539        // Otherwise the client computes hrr_accept_confirmation as described in Section
540        // 7.2.1
541        let confirmation_transcript = self.inner_hello_transcript.clone();
542        let mut confirmation_transcript =
543            confirmation_transcript.start_hash(cs.common.hash_provider);
544        confirmation_transcript.rollup_for_hrr();
545        confirmation_transcript.add_message(&Self::hello_retry_request_conf(hrr));
546
547        let derived = server_ech_hrr_confirmation_secret(
548            cs.hkdf_provider,
549            &self.inner_hello_random.0,
550            confirmation_transcript.current_hash(),
551        );
552
553        match ConstantTimeEq::ct_eq(derived.as_ref(), ech_conf.bytes()).into() {
554            true => {
555                trace!("ECH accepted by server in hello retry request");
556                Ok(true)
557            }
558            false => {
559                trace!("ECH rejected by server in hello retry request");
560                Ok(false)
561            }
562        }
563    }
564
565    /// Update the ECH context inner hello transcript based on a received hello retry request message.
566    ///
567    /// This will start the in-progress transcript using the given `hash`, convert it into an HRR
568    /// buffer, and then add the hello retry message `m`.
569    pub(crate) fn transcript_hrr_update(
570        &mut self,
571        hash: &'static dyn Hash,
572        m: &Message<'_>,
573        proof: &HandshakeAlignedProof,
574    ) {
575        trace!("Updating ECH inner transcript for HRR");
576
577        let inner_transcript = self
578            .inner_hello_transcript
579            .clone()
580            .start_hash(hash);
581
582        let mut inner_transcript_buffer = inner_transcript.into_hrr_buffer(proof);
583        inner_transcript_buffer.add_message(m);
584        self.inner_hello_transcript = inner_transcript_buffer;
585    }
586
587    // See https://datatracker.ietf.org/doc/html/rfc9849#name-grease-psk
588    pub(super) fn grease_psk(&mut self, psk_offer: &mut PresharedKeyOffer) -> Result<(), Error> {
589        match &self.grease_psk_identities {
590            // This is a retry hello: re-offer the identities and ages from the first hello,
591            // as a genuine PSK offer would. Only the binders are regenerated below; a fresh
592            // GREASE PSK here would "stick out" to an attacker triggering a retry.
593            Some(identities) => psk_offer.identities = identities.clone(),
594            None => {
595                for ident in psk_offer.identities.iter_mut() {
596                    // "For each PSK identity advertised in the ClientHelloInner, the
597                    // client generates a random PSK identity with the same length."
598                    let Some(identity) = ident.identity.as_mut() else {
599                        unreachable!();
600                    };
601                    self.secure_random.fill(identity)?;
602
603                    // "It also generates a random, 32-bit, unsigned integer to use as
604                    // the obfuscated_ticket_age."
605                    let mut ticket_age = [0_u8; 4];
606                    self.secure_random
607                        .fill(&mut ticket_age)?;
608                    ident.obfuscated_ticket_age = u32::from_be_bytes(ticket_age);
609                }
610
611                self.grease_psk_identities = Some(psk_offer.identities.clone());
612            }
613        }
614
615        // "Likewise, for each inner PSK binder, the client generates a random string
616        // of the same length."
617        psk_offer.binders = psk_offer
618            .binders
619            .iter()
620            .map(|old_binder| {
621                // We can't access the wrapped binder PresharedKeyBinder's PayloadU8 mutably,
622                // so we construct new PresharedKeyBinder's from scratch with the same length.
623                let mut new_binder = vec![0; old_binder.as_ref().len()];
624                self.secure_random
625                    .fill(&mut new_binder)?;
626                Ok::<PresharedKeyBinder, Error>(PresharedKeyBinder::from(new_binder))
627            })
628            .collect::<Result<_, _>>()?;
629        Ok(())
630    }
631
632    // 5.1 "Encoding the ClientHelloInner"
633    fn encode_inner_hello(
634        &mut self,
635        outer_hello: &ClientHelloPayload,
636        retryreq: Option<&HelloRetryRequest>,
637        resuming: Option<&Retrieved<&Tls13Session>>,
638    ) -> Result<Vec<u8>, Error> {
639        // Start building an inner hello using the outer_hello as a template.
640        let mut inner_hello = ClientHelloPayload {
641            // Some information is copied over as-is.
642            client_version: outer_hello.client_version,
643
644            // Set the inner hello random to the one we generated when creating the ECH state.
645            // We hold on to the inner_hello_random in the ECH state to use later for confirming
646            // whether ECH was accepted or not.
647            random: self.inner_hello_random,
648            session_id: outer_hello.session_id,
649
650            // We remove the empty renegotiation info SCSV from the outer hello's ciphersuite.
651            // Similar to the TLS 1.2 specific extensions we will filter out, this is seen as a
652            // TLS 1.2 only feature by bogo.
653            cipher_suites: outer_hello
654                .cipher_suites
655                .iter()
656                .filter(|cs| **cs != CipherSuite::TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
657                .copied()
658                .collect(),
659            compression_methods: outer_hello.compression_methods.clone(),
660
661            // We will build up the included extensions ourselves.
662            extensions: Box::new(ClientExtensions::default()),
663        };
664
665        inner_hello.order_seed = outer_hello.order_seed;
666
667        // The inner hello will always have an inner variant of the ECH extension added.
668        // See Section 6.1 rule 4.
669        inner_hello.encrypted_client_hello = Some(EncryptedClientHello::Inner);
670
671        let inner_sni = match &self.inner_name {
672            // The inner hello only gets a SNI value if enable_sni is true and the inner name
673            // is a domain name (not an IP address).
674            ServerName::DnsName(dns_name) if self.enable_sni => Some(dns_name),
675            _ => None,
676        };
677
678        // Now we consider each of the outer hello's extensions - we can either:
679        // 1. Omit the extension if it isn't appropriate (e.g. is a TLS 1.2 extension).
680        // 2. Add the extension to the inner hello as-is.
681        // 3. Compress the extension, by collecting it into a list of to-be-compressed
682        //    extensions we'll handle separately.
683        let outer_extensions = outer_hello.used_extensions_in_encoding_order();
684        let mut compressed_exts = Vec::with_capacity(outer_extensions.len());
685        for ext in outer_extensions {
686            // Some outer hello extensions are only useful in the context where a TLS 1.3
687            // connection allows TLS 1.2. This isn't the case for ECH so we skip adding them
688            // to the inner hello.
689            if matches!(
690                ext,
691                ExtensionType::ExtendedMainSecret
692                    | ExtensionType::SessionTicket
693                    | ExtensionType::ECPointFormats
694            ) {
695                continue;
696            }
697
698            if ext == ExtensionType::ServerName {
699                // We may want to replace the outer hello SNI with our own inner hello specific SNI.
700                if let Some(sni_value) = inner_sni {
701                    inner_hello.server_name = Some(ServerNamePayload::from(sni_value));
702                }
703                // We don't want to add, or compress, the SNI from the outer hello.
704                continue;
705            }
706
707            // Compressed extensions need to be put aside to include in one contiguous block.
708            // Uncompressed extensions get added directly to the inner hello.
709            if ext.ech_compress() {
710                compressed_exts.push(ext);
711            }
712
713            inner_hello.clone_one(outer_hello, ext);
714        }
715
716        // We've added all the uncompressed extensions. Now we need to add the contiguous
717        // block of to-be-compressed extensions.
718        inner_hello.contiguous_extensions = compressed_exts.clone();
719
720        // Note which extensions we're sending in the inner hello. This may differ from
721        // the outer hello (e.g. the inner hello may omit SNI while the outer hello will
722        // always have the ECH cover name in SNI).
723        self.sent_extensions = inner_hello.collect_used();
724
725        // If we're resuming, we need to update the PSK binder in the inner hello.
726        if let Some(resuming) = resuming.as_ref() {
727            let mut chp = HandshakeMessagePayload(HandshakePayload::ClientHello(inner_hello));
728
729            let key_schedule =
730                KeyScheduleEarlyClient::new(resuming.suite, resuming.secret.bytes())?;
731            tls13::fill_in_psk_binder(&key_schedule, &self.inner_hello_transcript, &mut chp);
732            self.early_data_key_schedule = Some(key_schedule);
733
734            // fill_in_psk_binder works on an owned HandshakeMessagePayload, so we need to
735            // extract our inner hello back out of it to retain ownership.
736            inner_hello = match chp.0 {
737                HandshakePayload::ClientHello(chp) => chp,
738                // Safety: we construct the HMP above and know its type unconditionally.
739                _ => unreachable!(),
740            };
741        }
742
743        trace!("ECH Inner Hello: {inner_hello:#?}");
744
745        // Encode the inner hello according to the rules required for ECH. This differs
746        // from the standard encoding in several ways. Notably this is where we will
747        // replace the block of contiguous to-be-compressed extensions with a marker.
748        let mut encoded_hello = inner_hello.ech_inner_encoding(compressed_exts);
749
750        // Calculate padding
751        // max_name_len = L
752        let max_name_len = usize::from(self.maximum_name_length);
753        let max_name_len = if max_name_len > 0 { max_name_len } else { 255 };
754
755        let name_padding_len = match &inner_hello.server_name {
756            Some(ServerNamePayload::SingleDnsName(name)) => {
757                // name.len() = D
758                // max(0, L - D)
759                Ord::max(0, max_name_len.saturating_sub(name.as_ref().len()))
760            }
761            // L + 9
762            // "This is the length of a "server_name" extension with an L-byte name."
763            _ => max_name_len + 9,
764        };
765        encoded_hello.extend(iter::repeat_n(0, name_padding_len));
766
767        // Let L be the length of the EncodedClientHelloInner with all the padding computed so far
768        // Let N = 31 - ((L - 1) % 32) and add N bytes of padding.
769        let padding_len = 31 - ((encoded_hello.len() - 1) % 32);
770        encoded_hello.extend(iter::repeat_n(0, padding_len));
771
772        // Construct the inner hello message that will be used for the transcript.
773        let inner_hello_msg = Message {
774            version: match retryreq {
775                // <https://datatracker.ietf.org/doc/html/rfc9846#section-5.1>:
776                // "This value MUST be set to 0x0303 for all records generated
777                //  by a TLS 1.3 implementation ..."
778                Some(_) => EncodableVersion::Legacy(ProtocolVersion::TLSv1_2),
779                // "... other than an initial ClientHello (i.e., one not
780                // generated after a HelloRetryRequest), where it MAY also be
781                // 0x0301 for compatibility purposes"
782                //
783                // (retryreq == None means we're in the "initial ClientHello" case)
784                None => EncodableVersion::InitialClientHello(Protocol::Tcp),
785            },
786            payload: MessagePayload::handshake(HandshakeMessagePayload(
787                HandshakePayload::ClientHello(inner_hello),
788            )),
789        };
790
791        // Update the inner transcript buffer with the inner hello message.
792        self.inner_hello_transcript
793            .add_message(&inner_hello_msg);
794
795        Ok(encoded_hello)
796    }
797
798    fn server_hello_conf(
799        server_hello: &ServerHelloPayload,
800        server_hello_encoded: &Payload<'_>,
801    ) -> Message<'static> {
802        // The confirmation is computed over the server hello, which has had
803        // its `random` field altered to zero the final 8 bytes.
804        //
805        // nb. we don't require that we can round-trip a `ServerHelloPayload`, to
806        // allow for efficiency in its in-memory representation.  That means
807        // we operate here on the received encoding, as the confirmation needs
808        // to be computed on that.
809        let mut encoded = server_hello_encoded.clone().into_vec();
810        encoded[SERVER_HELLO_ECH_CONFIRMATION_SPAN].fill(0x00);
811
812        Message {
813            version: EncodableVersion::Legacy(ProtocolVersion::TLSv1_3),
814            payload: MessagePayload::Handshake {
815                encoded: Payload::Owned(encoded),
816                parsed: HandshakeMessagePayload(HandshakePayload::ServerHello(
817                    server_hello.clone(),
818                )),
819            },
820        }
821    }
822
823    fn hello_retry_request_conf(retry_req: &HelloRetryRequest) -> Message<'_> {
824        Self::ech_conf_message(HandshakeMessagePayload(
825            HandshakePayload::HelloRetryRequest(retry_req.clone()),
826        ))
827    }
828
829    fn ech_conf_message(hmp: HandshakeMessagePayload<'_>) -> Message<'_> {
830        let mut hmp_encoded = Vec::new();
831        hmp.payload_encode(&mut hmp_encoded, Encoding::EchConfirmation);
832        Message {
833            version: EncodableVersion::Legacy(ProtocolVersion::TLSv1_3),
834            payload: MessagePayload::Handshake {
835                encoded: Payload::new(hmp_encoded),
836                parsed: hmp,
837            },
838        }
839    }
840}
841
842/// The last eight bytes of the ServerHello's random, taken from a Handshake message containing it.
843///
844/// This has:
845/// - a HandshakeType (1 byte),
846/// - an exterior length (3 bytes),
847/// - the legacy_version (2 bytes), and
848/// - the balance of the random field (24 bytes).
849const SERVER_HELLO_ECH_CONFIRMATION_SPAN: core::ops::Range<usize> =
850    (1 + 3 + 2 + 24)..(1 + 3 + 2 + 32);
851
852/// Returned from EchState::confirm_acceptance when the server has accepted the ECH offer.
853///
854/// Holds the state required to continue the handshake with the inner hello from the ECH offer.
855pub(crate) struct EchAccepted {
856    pub(crate) transcript: HandshakeHash,
857    pub(crate) random: Random,
858    pub(crate) sent_extensions: Vec<ExtensionType>,
859}
860
861#[cfg(test)]
862mod tests {
863    use core::sync::atomic::{AtomicU8, Ordering};
864    use core::time::Duration;
865    use std::string::String;
866
867    use pki_types::{CertificateDer, SubjectPublicKeyInfoDer, UnixTime};
868
869    use super::*;
870    use crate::client::{
871        ClientSessionKey, ClientSessionMemoryCache, ClientSessionStore, Resumption,
872        Tls13ClientSessionInput, VerifiedIdentity,
873    };
874    use crate::conn::Connection;
875    use crate::crypto::cipher::Record;
876    use crate::crypto::hpke::{HpkeAead, HpkeKdf};
877    use crate::crypto::{CipherSuite, GetRandomFailed, Identity, TEST_PROVIDER, tls13_only};
878    use crate::msgs::{
879        Compression, HelloRetryRequestExtensions, NewSessionTicketPayloadTls13, Random, Reader,
880        ServerExtensions, SessionId,
881    };
882    use crate::sync::Arc;
883    use crate::tls13::Tls13ProtocolSuite;
884    use crate::{RootCertStore, VecInput};
885
886    #[test]
887    fn server_hello_conf_alters_server_hello_random() {
888        let server_hello = ServerHelloPayload {
889            legacy_version: ProtocolVersion::TLSv1_2,
890            random: Random([0xffu8; 32]),
891            session_id: SessionId::empty(),
892            cipher_suite: CipherSuite::TLS13_AES_256_GCM_SHA384,
893            compression_method: Compression::Null,
894            extensions: Box::new(ServerExtensions::default()),
895        };
896        let message = Message {
897            version: EncodableVersion::Legacy(ProtocolVersion::TLSv1_3),
898            payload: MessagePayload::handshake(HandshakeMessagePayload(
899                HandshakePayload::ServerHello(server_hello.clone()),
900            )),
901        };
902        let Message {
903            payload:
904                MessagePayload::Handshake {
905                    encoded: server_hello_encoded_before,
906                    ..
907                },
908            ..
909        } = &message
910        else {
911            unreachable!("ServerHello is a handshake message");
912        };
913
914        let message = EchState::server_hello_conf(&server_hello, server_hello_encoded_before);
915
916        let Message {
917            payload:
918                MessagePayload::Handshake {
919                    encoded: server_hello_encoded_after,
920                    ..
921                },
922            ..
923        } = &message
924        else {
925            unreachable!("ServerHello is a handshake message");
926        };
927
928        assert_eq!(
929            std::format!("{server_hello_encoded_before:x?}"),
930            "020000280303ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001302000000",
931            "beforehand eight bytes at end of Random should be 0xff here ^^^^^^^^^^^^^^^^            "
932        );
933        assert_eq!(
934            std::format!("{server_hello_encoded_after:x?}"),
935            "020000280303ffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000001302000000",
936            "                          afterwards those bytes are zeroed ^^^^^^^^^^^^^^^^            "
937        );
938    }
939
940    #[test]
941    fn inner_client_hello_length_conceals_inner_name_length() {
942        let base_inner_len = inner_hello_encoding_for_name(dns_name_of_len(1), true)
943            .unwrap()
944            .len();
945        assert!(
946            base_inner_len % 32 == 0,
947            "inner hello length must be 32-byte padded"
948        );
949        assert!(
950            base_inner_len >= 256,
951            "inner hello must include inner name and its padding"
952        );
953
954        for inner_name_len in 1..251 {
955            assert_eq!(
956                inner_hello_encoding_for_name(dns_name_of_len(inner_name_len), true)
957                    .unwrap()
958                    .len(),
959                base_inner_len,
960                "all inner hello lengths must be invariant wrt inner name length"
961            );
962        }
963    }
964
965    #[test]
966    fn inner_client_hello_length_does_not_leak_length_of_omitted_inner_name() {
967        let base_inner_len = inner_hello_encoding_for_name(dns_name_of_len(1), false)
968            .unwrap()
969            .len();
970        assert!(
971            base_inner_len % 32 == 0,
972            "inner hello length must be 32-byte padded"
973        );
974        assert!(
975            base_inner_len >= 256,
976            "inner hello must include maximum_name_length bytes of padding"
977        );
978
979        for inner_name_len in 1..251 {
980            assert_eq!(
981                inner_hello_encoding_for_name(dns_name_of_len(inner_name_len), false)
982                    .unwrap()
983                    .len(),
984                base_inner_len,
985                "all inner hello lengths must be invariant wrt inner name length"
986            );
987        }
988    }
989
990    #[test]
991    fn ech_rejected_by_hello_retry_request_conceals_inner_psk() {
992        let mut roots = RootCertStore::empty();
993        roots
994            .add(CertificateDer::from_slice(include_bytes!(
995                "../../../test-ca/rsa-2048/ca.der"
996            )))
997            .unwrap();
998
999        // `TEST_PROVIDER`'s fixed-fill `SecureRandom` would mask a regression here: a
1000        // fresh GREASE PSK generated for the retry would repeat the first hello's
1001        // identity by happenstance. A counter makes consecutive fills distinct.
1002        let mut provider = tls13_only(TEST_PROVIDER.clone());
1003        provider.secure_random = &CountingRandom;
1004
1005        let config = ClientConfig::builder(Arc::new(provider))
1006            .with_ech(EchMode::Enable(EchConfig {
1007                config: EchConfigPayload::V18(EchConfigContents {
1008                    key_config: HpkeKeyConfig {
1009                        config_id: 0,
1010                        kem_id: MockHpke::SUITE.kem,
1011                        public_key: vec![0; 32].into(),
1012                        symmetric_cipher_suites: vec![MockHpke::SUITE.sym],
1013                    },
1014                    maximum_name_length: 255,
1015                    public_name: DnsName::try_from("public.example.com").unwrap(),
1016                    extensions: vec![],
1017                }),
1018                suite: &MockHpke,
1019            }))
1020            .with_root_certificates(roots)
1021            .with_no_client_auth()
1022            .unwrap();
1023        let store = Arc::new(ClientSessionMemoryCache::new(256));
1024        let config = Arc::new(ClientConfig {
1025            resumption: Resumption::store(store.clone()),
1026            ..config
1027        });
1028
1029        // cache a ticket for the concealed inner name
1030        let server_name = ServerName::try_from("inner.example.com").unwrap();
1031        store.insert_tls13_ticket(
1032            ClientSessionKey {
1033                config_hash: config.config_hash(),
1034                server_name: server_name.clone(),
1035            },
1036            Tls13Session::new(
1037                &NewSessionTicketPayloadTls13::new(
1038                    Duration::from_secs(1800),
1039                    0x1234_5678,
1040                    [0u8; 32],
1041                    TICKET.to_vec(),
1042                ),
1043                Tls13ClientSessionInput {
1044                    suite: Tls13ProtocolSuite::Tcp(TEST_PROVIDER.tls13_cipher_suites[0]),
1045                    peer_identity: VerifiedIdentity::assertion(Identity::RawPublicKey(
1046                        SubjectPublicKeyInfoDer::from(&b"spki"[..]),
1047                    )),
1048                    quic_params: None,
1049                },
1050                &[0x55; 32],
1051                UnixTime::now(),
1052            ),
1053        );
1054
1055        let mut first_flight = Vec::new();
1056        let mut conn = config
1057            .connect(server_name)
1058            .build(&mut first_flight)
1059            .unwrap();
1060
1061        // the ticket belongs to the concealed inner name, so the outer hello offers
1062        // a GREASE PSK in its place
1063        let first = client_hello_in(&first_flight);
1064        assert_ne!(psk_identity(&first), TICKET);
1065
1066        // a HelloRetryRequest without `encrypted_client_hello` rejects our ECH offer
1067        let hrr = Message {
1068            version: EncodableVersion::Legacy(ProtocolVersion::TLSv1_2),
1069            payload: MessagePayload::handshake(HandshakeMessagePayload(
1070                HandshakePayload::HelloRetryRequest(HelloRetryRequest {
1071                    legacy_version: ProtocolVersion::TLSv1_2,
1072                    session_id: first.session_id,
1073                    cipher_suite: first.cipher_suites[0],
1074                    extensions: HelloRetryRequestExtensions {
1075                        cookie: Some(SizedPayload::from(vec![1, 2, 3, 4])),
1076                        supported_versions: Some(ProtocolVersion::TLSv1_3),
1077                        ..HelloRetryRequestExtensions::default()
1078                    },
1079                }),
1080            )),
1081        };
1082        let mut input = VecInput::default();
1083        input
1084            .read(&mut hrr.into_wire_bytes().as_slice())
1085            .unwrap();
1086        let mut retry_flight = Vec::new();
1087        conn.read_tls(&mut input, &mut retry_flight)
1088            .handle_all(&mut Vec::new())
1089            .unwrap();
1090
1091        // we continue with a second outer hello: it must conceal the ticket too, and
1092        // must re-offer the first hello's GREASE identity as a genuine PSK offer would
1093        let second = client_hello_in(&retry_flight);
1094        assert_ne!(psk_identity(&second), TICKET);
1095        assert_eq!(psk_identity(&second), psk_identity(&first));
1096
1097        fn client_hello_in(bytes: &[u8]) -> ClientHelloPayload {
1098            let mut reader = Reader::new(bytes);
1099            while reader.any_left() {
1100                let record = Record::<Payload<'_>>::read(&mut reader)
1101                    .unwrap()
1102                    .into_owned();
1103                if let Ok(Message {
1104                    payload:
1105                        MessagePayload::Handshake {
1106                            parsed: HandshakeMessagePayload(HandshakePayload::ClientHello(ch)),
1107                            ..
1108                        },
1109                    ..
1110                }) = Message::try_from(&record)
1111                {
1112                    return ch;
1113                }
1114            }
1115            panic!("no ClientHello written");
1116        }
1117
1118        fn psk_identity(hello: &ClientHelloPayload) -> &[u8] {
1119            hello
1120                .preshared_key_offer
1121                .as_ref()
1122                .unwrap()
1123                .identities[0]
1124                .identity
1125                .bytes()
1126        }
1127
1128        const TICKET: &[u8] = b"inner name resumption ticket";
1129
1130        #[derive(Debug)]
1131        struct CountingRandom;
1132
1133        impl SecureRandom for CountingRandom {
1134            fn fill(&self, bytes: &mut [u8]) -> Result<(), GetRandomFailed> {
1135                static COUNTER: AtomicU8 = AtomicU8::new(0);
1136                for byte in bytes.iter_mut() {
1137                    *byte = COUNTER.fetch_add(1, Ordering::Relaxed);
1138                }
1139                Ok(())
1140            }
1141        }
1142    }
1143
1144    fn inner_hello_encoding_for_name(
1145        name: DnsName<'static>,
1146        enable_sni: bool,
1147    ) -> Result<Vec<u8>, Error> {
1148        let config = EchConfig {
1149            config: EchConfigPayload::V18(EchConfigContents {
1150                key_config: HpkeKeyConfig {
1151                    config_id: 0,
1152                    kem_id: MockHpke::SUITE.kem,
1153                    public_key: vec![0; 32].into(),
1154                    symmetric_cipher_suites: vec![],
1155                },
1156                maximum_name_length: 255,
1157                public_name: DnsName::try_from("public").unwrap(),
1158                extensions: vec![],
1159            }),
1160            suite: &MockHpke,
1161        };
1162
1163        EchState::new(
1164            &config,
1165            ServerName::from(name.clone()),
1166            false,
1167            TEST_PROVIDER.secure_random,
1168            enable_sni,
1169        )
1170        .unwrap()
1171        .encode_inner_hello(
1172            &ClientHelloPayload {
1173                client_version: ProtocolVersion::TLSv1_3,
1174                random: Random([0u8; 32]),
1175                session_id: SessionId::empty(),
1176                cipher_suites: vec![],
1177                compression_methods: vec![Compression::Null],
1178                extensions: Box::new(ClientExtensions {
1179                    server_name: Some(ServerNamePayload::from(&name)),
1180                    ..Default::default()
1181                }),
1182            },
1183            None,
1184            None,
1185        )
1186    }
1187
1188    fn dns_name_of_len(mut len: usize) -> DnsName<'static> {
1189        let mut s = String::new();
1190        let labels = len.div_ceil(63);
1191        for _ in 0..labels {
1192            let chars = Ord::min(len, 63);
1193            len -= chars;
1194            for _ in 0..chars {
1195                s.push('a');
1196            }
1197            if len != 0 {
1198                s.push('.');
1199            }
1200        }
1201        DnsName::try_from(s).unwrap()
1202    }
1203
1204    #[derive(Debug)]
1205    struct MockHpke;
1206
1207    impl MockHpke {
1208        const SUITE: HpkeSuite = HpkeSuite {
1209            kem: HpkeKem::DHKEM_P256_HKDF_SHA256,
1210            sym: HpkeSymmetricCipherSuite {
1211                kdf_id: HpkeKdf::HKDF_SHA256,
1212                aead_id: HpkeAead::AES_128_GCM,
1213            },
1214        };
1215    }
1216
1217    impl Hpke for MockHpke {
1218        #[cfg_attr(coverage_nightly, coverage(off))]
1219        fn seal(
1220            &self,
1221            _info: &[u8],
1222            _aad: &[u8],
1223            _plaintext: &[u8],
1224            _pub_key: &HpkePublicKey,
1225        ) -> Result<(EncapsulatedSecret, Vec<u8>), Error> {
1226            todo!()
1227        }
1228
1229        fn setup_sealer(
1230            &self,
1231            _info: &[u8],
1232            _pub_key: &HpkePublicKey,
1233        ) -> Result<(EncapsulatedSecret, Box<dyn HpkeSealer + 'static>), Error> {
1234            Ok((EncapsulatedSecret(vec![]), Box::new(MockHpkeSealer)))
1235        }
1236
1237        #[cfg_attr(coverage_nightly, coverage(off))]
1238        fn open(
1239            &self,
1240            _enc: &EncapsulatedSecret,
1241            _info: &[u8],
1242            _aad: &[u8],
1243            _ciphertext: &[u8],
1244            _secret_key: &crate::crypto::hpke::HpkePrivateKey,
1245        ) -> Result<Vec<u8>, Error> {
1246            todo!()
1247        }
1248
1249        #[cfg_attr(coverage_nightly, coverage(off))]
1250        fn setup_opener(
1251            &self,
1252            _enc: &EncapsulatedSecret,
1253            _info: &[u8],
1254            _secret_key: &crate::crypto::hpke::HpkePrivateKey,
1255        ) -> Result<Box<dyn crate::crypto::hpke::HpkeOpener + 'static>, Error> {
1256            todo!()
1257        }
1258
1259        #[cfg_attr(coverage_nightly, coverage(off))]
1260        fn generate_key_pair(
1261            &self,
1262        ) -> Result<(HpkePublicKey, crate::crypto::hpke::HpkePrivateKey), Error> {
1263            todo!()
1264        }
1265
1266        fn suite(&self) -> HpkeSuite {
1267            Self::SUITE
1268        }
1269    }
1270
1271    #[derive(Debug)]
1272    struct MockHpkeSealer;
1273
1274    impl HpkeSealer for MockHpkeSealer {
1275        fn seal(&mut self, _aad: &[u8], plaintext: &[u8]) -> Result<Vec<u8>, Error> {
1276            // ciphertext length as if sealed with the AEAD named in `MockHpke::SUITE`
1277            Ok(vec![0xff; plaintext.len() + 16])
1278        }
1279    }
1280}