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