rustls 0.24.0-dev.1

Rustls is a modern TLS library written in Rust.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
use alloc::borrow::{Cow, ToOwned};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::borrow::Borrow;
use core::fmt;

use pki_types::DnsName;

use super::config::{CipherSuiteSelector, VersionSuiteSelector};
use super::{ClientHello, CommonServerSessionValue, ServerConfig, tls12, tls13};
use crate::SupportedCipherSuite;
use crate::common_state::{Event, Output, OutputEvent, Protocol};
use crate::conn::{ConnectionRandoms, Input};
use crate::crypto::hash::Hash;
use crate::crypto::kx::{KeyExchangeAlgorithm, NamedGroup, SupportedKxGroup};
use crate::crypto::{CipherSuite, CryptoProvider, SelectedCredential, SignatureScheme};
use crate::enums::{ApplicationProtocol, CertificateType, HandshakeType, ProtocolVersion};
use crate::error::{ApiMisuse, Error, PeerIncompatible, PeerMisbehaved};
use crate::hash_hs::{HandshakeHash, HandshakeHashBuffer};
use crate::kernel::KernelState;
use crate::log::{debug, trace};
use crate::msgs::{
    ClientHelloPayload, Compression, HandshakeAlignedProof, HandshakeMessagePayload,
    HandshakePayload, Message, MessagePayload, Random, ServerExtensions, ServerExtensionsInput,
    ServerNamePayload, SessionId, SingleProtocolName, TransportParameters,
};
use crate::sealed::Sealed;
use crate::suites::{PartiallyExtractedSecrets, Suite};
use crate::sync::Arc;
use crate::tls12::Tls12CipherSuite;
use crate::tls13::Tls13CipherSuite;
use crate::tls13::key_schedule::KeyScheduleTrafficSend;

pub(crate) enum ServerState {
    /// Reading an entire ClientHello
    ///
    /// Validations that do not rely on a config can be performed here, but most are
    /// deferred until [`ServerState::ClientHello`].
    ReadClientHello(ReadClientHello),

    /// Choose a [`ServerConfig`] based on the received ClientHello.
    ChooseConfig(Box<ChooseConfig>),

    /// Processing the received ClientHello.
    ClientHello(Box<ExpectClientHello>),
    Tls12(tls12::Tls12State),
    Tls13(tls13::Tls13State),
}

impl ServerState {
    pub(crate) fn set_resumption_data(&mut self, resumption_data: &[u8]) -> Result<(), Error> {
        match self {
            Self::ReadClientHello(e) => e.set_resumption_data(resumption_data),
            Self::ChooseConfig(e) => e.set_resumption_data(resumption_data),
            Self::ClientHello(e) => e.set_resumption_data(resumption_data),
            _ => Err(ApiMisuse::ResumptionDataProvidedTooLate.into()),
        }
    }
}

impl crate::conn::StateMachine for ServerState {
    fn handle<'m>(self, input: Input<'m>, output: &mut dyn Output<'m>) -> Result<Self, Error> {
        match self {
            Self::ReadClientHello(r) => r.handle(input, output),
            Self::ChooseConfig(_) => {
                Err(Error::Unreachable("ChooseConfig cannot process a message"))
            }
            Self::ClientHello(e) => e.handle(input, output),
            Self::Tls12(sm) => sm.handle(input, output),
            Self::Tls13(sm) => sm.handle(input, output),
        }
    }

    fn wants_input(&self) -> bool {
        !matches!(self, Self::ChooseConfig(_))
    }

    fn is_traffic(&self) -> bool {
        matches!(
            self,
            Self::Tls12(tls12::Tls12State::Traffic(..))
                | Self::Tls13(tls13::Tls13State::Traffic(..) | tls13::Tls13State::QuicTraffic(..))
        )
    }

    fn handle_decrypt_error(&mut self) {}

    fn into_external_state(
        self,
        send_keys: &Option<Box<KeyScheduleTrafficSend>>,
    ) -> Result<(PartiallyExtractedSecrets, Box<dyn KernelState + 'static>), Error> {
        match self {
            Self::Tls13(tls13::Tls13State::Traffic(e)) => e.into_external_state(send_keys),
            Self::Tls12(tls12::Tls12State::Traffic(e)) => e.into_external_state(send_keys),
            _ => Err(Error::HandshakeNotComplete),
        }
    }
}

pub(super) struct Tls12Extensions {
    pub(super) alpn_protocol: Option<ApplicationProtocol<'static>>,
    pub(super) send_ticket: bool,
}

impl Tls12Extensions {
    pub(super) fn new(
        extra_exts: ServerExtensionsInput,
        ocsp_response: &mut Option<&[u8]>,
        resumedata: Option<&CommonServerSessionValue<'_>>,
        hello: &ClientHelloPayload,
        output: &mut dyn Output<'_>,
        using_ems: bool,
        config: &ServerConfig,
    ) -> Result<(Self, Box<ServerExtensions<'static>>), Error> {
        let ep = ExtensionProcessing::new(hello, config);
        let (alpn_protocol, mut extensions) =
            ep.process_common(extra_exts, output, ocsp_response, resumedata)?;

        // Renegotiation.
        // (We don't do reneg at all, but would support the secure version if we did.)
        if hello.renegotiation_info.is_some()
            || hello
                .cipher_suites
                .contains(&CipherSuite::TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
        {
            extensions.renegotiation_info = Some(Vec::new().into());
        }

        // Tickets:
        // If we get any SessionTicket extension and have tickets enabled,
        // we send an ack.
        let send_ticket = if hello.session_ticket.is_some() && config.ticketer.is_some() {
            extensions.session_ticket_ack = Some(());
            true
        } else {
            false
        };

        // Confirm use of EMS if offered.
        if using_ems {
            extensions.extended_master_secret_ack = Some(());
        }

        // Send confirmation of OCSP staple request if we will send one.
        if let Some([_, ..]) = ocsp_response {
            extensions.certificate_status_request_ack = Some(());
        }

        let out = Self {
            alpn_protocol,
            send_ticket,
        };

        Ok((out, extensions))
    }
}

pub(super) struct Tls13Extensions {
    pub(super) certificate_types: CertificateTypes,
    pub(super) alpn_protocol: Option<ApplicationProtocol<'static>>,
}

impl Tls13Extensions {
    pub(super) fn new(
        extra_exts: ServerExtensionsInput,
        ocsp_response: &mut Option<&[u8]>,
        resumedata: Option<&CommonServerSessionValue<'_>>,
        hello: &ClientHelloPayload,
        output: &mut dyn Output<'_>,
        config: &ServerConfig,
    ) -> Result<(Self, Box<ServerExtensions<'static>>), Error> {
        let ep = ExtensionProcessing::new(hello, config);
        let (alpn_protocol, mut extensions) =
            ep.process_common(extra_exts, output, ocsp_response, resumedata)?;

        let expected_client_type = select_cert_type(
            hello
                .client_certificate_types
                .as_deref(),
            config
                .verifier
                .supported_certificate_types(),
        )?;

        let expected_server_type = select_cert_type(
            hello
                .server_certificate_types
                .as_deref(),
            config
                .cert_resolver
                .supported_certificate_types(),
        )?;

        if hello.client_certificate_types.is_some() && config.verifier.offer_client_auth() {
            extensions.client_certificate_type = Some(expected_client_type);
        }
        if hello.server_certificate_types.is_some() {
            extensions.server_certificate_type = Some(expected_server_type);
        }

        let out = Self {
            certificate_types: CertificateTypes {
                client: expected_client_type,
            },
            alpn_protocol,
        };

        Ok((out, extensions))
    }
}

struct ExtensionProcessing<'a> {
    config: &'a ServerConfig,
    hello: &'a ClientHelloPayload,
}

impl<'a> ExtensionProcessing<'a> {
    fn new(client_hello: &'a ClientHelloPayload, config: &'a ServerConfig) -> Self {
        Self {
            config,
            hello: client_hello,
        }
    }

    fn process_common(
        self,
        extra_exts: ServerExtensionsInput,
        output: &mut dyn Output<'_>,
        ocsp_response: &mut Option<&[u8]>,
        resumedata: Option<&CommonServerSessionValue<'_>>,
    ) -> Result<
        (
            Option<ApplicationProtocol<'static>>,
            Box<ServerExtensions<'static>>,
        ),
        Error,
    > {
        let Self { config, hello } = self;
        let mut extensions = Box::new(ServerExtensions::default());

        let ServerExtensionsInput {
            transport_parameters,
        } = extra_exts;
        if let Some(TransportParameters::Quic(v)) = transport_parameters {
            extensions.transport_parameters = Some(v);
        }

        // ALPN
        let our_protocols = &config.alpn_protocols;
        let chosen_protocol = if let Some(their_protocols) = &hello.protocols {
            if let Some(selected_protocol) = our_protocols.iter().find(|ours| {
                their_protocols
                    .iter()
                    .any(|theirs| theirs.as_ref() == ours.as_ref())
            }) {
                debug!("Chosen ALPN protocol {selected_protocol:?}");

                Some(selected_protocol)
            } else if !our_protocols.is_empty() {
                return Err(Error::NoApplicationProtocol);
            } else {
                None
            }
        } else {
            None
        };

        // Enact ALPN selection by telling peer and high-level API.
        if let Some(protocol) = &chosen_protocol {
            extensions.selected_protocol = Some(SingleProtocolName::new((*protocol).to_owned()));
            output.output(OutputEvent::ApplicationProtocol((*protocol).to_owned()));
        }

        if let Some(quic) = output.quic() {
            // QUIC has strict ALPN, unlike TLS's more backwards-compatible behavior. RFC 9001
            // says: "The server MUST treat the inability to select a compatible application
            // protocol as a connection error of type 0x0178". We judge that ALPN was desired
            // (rather than some out-of-band protocol negotiation mechanism) if and only if any ALPN
            // protocols were configured locally or offered by the client. This helps prevent
            // successful establishment of connections between peers that can't understand
            // each other.
            if chosen_protocol.is_none() && (!our_protocols.is_empty() || hello.protocols.is_some())
            {
                return Err(Error::NoApplicationProtocol);
            }

            match hello.transport_parameters.as_ref() {
                Some(params) => quic.transport_parameters(params.to_owned().into_vec()),
                None => {
                    return Err(PeerMisbehaved::MissingQuicTransportParameters.into());
                }
            }
        }

        let for_resume = resumedata.is_some();
        // SNI
        if let (false, Some(ServerNamePayload::SingleDnsName(_))) = (for_resume, &hello.server_name)
        {
            extensions.server_name_ack = Some(());
        }

        // Discard OCSP response if it is not necessary.
        if for_resume
            || hello
                .certificate_status_request
                .is_none()
        {
            ocsp_response.take();
        }

        Ok((chosen_protocol.map(|p| p.to_owned()), extensions))
    }
}

fn select_cert_type(
    client: Option<&[CertificateType]>,
    server: &[CertificateType],
) -> Result<CertificateType, Error> {
    if server.is_empty() {
        return Err(ApiMisuse::NoSupportedCertificateTypes.into());
    }

    // https://www.rfc-editor.org/rfc/rfc7250#section-4.1
    // If the client has no remaining certificate types to send in
    // the client hello, other than the default X.509 type, it MUST omit the
    // client_certificate_type extension in the client hello.

    // If the client has no remaining certificate types to send in
    // the client hello, other than the default X.509 certificate type, it
    // MUST omit the entire server_certificate_type extension from the
    // client hello.
    let client = match client {
        Some([]) => {
            return Err(PeerIncompatible::IncorrectCertificateTypeExtension.into());
        }
        Some(c) => c,
        None => {
            return match server.contains(&CertificateType::X509) {
                true => Ok(CertificateType::X509),
                false => Err(PeerIncompatible::IncorrectCertificateTypeExtension.into()),
            };
        }
    };

    for &ct in client {
        if server.contains(&ct) {
            return Ok(ct);
        }
    }

    Err(PeerIncompatible::IncorrectCertificateTypeExtension.into())
}

pub(super) struct CertificateTypes {
    pub(super) client: CertificateType,
}

pub(crate) struct ReadClientHello {
    protocol: Protocol,
    resumption_data: Vec<u8>,
}

impl ReadClientHello {
    pub(crate) fn new(protocol: Protocol) -> Self {
        Self {
            protocol,
            resumption_data: Vec::new(),
        }
    }

    pub(crate) fn handle<'m>(
        self,
        input: Input<'m>,
        _output: &mut dyn Output<'_>,
    ) -> Result<ServerState, Error> {
        ClientHelloInput::from_input(&input)?;
        Ok(Box::new(ChooseConfig {
            client_hello: Input {
                message: input.message.into_owned(),
                aligned_handshake: input.aligned_handshake,
            },
            resumption_data: self.resumption_data,
            protocol: self.protocol,
        })
        .into())
    }

    fn set_resumption_data(&mut self, resumption_data: &[u8]) -> Result<(), Error> {
        self.resumption_data = resumption_data.to_vec();
        Ok(())
    }
}

impl From<ReadClientHello> for ServerState {
    fn from(value: ReadClientHello) -> Self {
        Self::ReadClientHello(value)
    }
}

pub(crate) struct ChooseConfig {
    protocol: Protocol,
    resumption_data: Vec<u8>,
    client_hello: Input<'static>,
}

impl ChooseConfig {
    pub(crate) fn use_config(
        self,
        config: Arc<ServerConfig>,
        extra_exts: ServerExtensionsInput,
        output: &mut dyn Output<'_>,
    ) -> Result<ServerState, Error> {
        ExpectClientHello::new(config, extra_exts, self.resumption_data, self.protocol)
            .with_input(ClientHelloInput::from_input(&self.client_hello)?, output)
    }

    pub(crate) fn client_hello(&self) -> ClientHello<'_> {
        let MessagePayload::Handshake {
            parsed: HandshakeMessagePayload(HandshakePayload::ClientHello(client_hello)),
            ..
        } = &self.client_hello.message.payload
        else {
            unreachable!();
        };

        let server_name = client_hello
            .server_name
            .as_ref()
            .and_then(ServerNamePayload::to_dns_name_normalized)
            .map(Cow::Owned);

        ClientHello::new(client_hello, None, server_name, None)
    }

    fn set_resumption_data(&mut self, resumption_data: &[u8]) -> Result<(), Error> {
        self.resumption_data = resumption_data.to_vec();
        Ok(())
    }
}

impl From<Box<ChooseConfig>> for ServerState {
    fn from(value: Box<ChooseConfig>) -> Self {
        Self::ChooseConfig(value)
    }
}

pub(crate) struct ExpectClientHello {
    pub(super) config: Arc<ServerConfig>,
    pub(super) protocol: Protocol,
    pub(super) extra_exts: ServerExtensionsInput,
    pub(super) transcript: HandshakeHashOrBuffer,
    pub(super) session_id: SessionId,
    pub(super) sni: Option<DnsName<'static>>,
    pub(super) resumption_data: Vec<u8>,
    pub(super) using_ems: bool,
    pub(super) done_retry: bool,
    pub(super) send_tickets: usize,
}

impl ExpectClientHello {
    pub(super) fn new(
        config: Arc<ServerConfig>,
        extra_exts: ServerExtensionsInput,
        resumption_data: Vec<u8>,
        protocol: Protocol,
    ) -> Self {
        let mut transcript_buffer = HandshakeHashBuffer::new();

        if config.verifier.offer_client_auth() {
            transcript_buffer.set_client_auth_enabled();
        }

        Self {
            config,
            protocol,
            extra_exts,
            transcript: HandshakeHashOrBuffer::Buffer(transcript_buffer),
            session_id: SessionId::empty(),
            sni: None,
            resumption_data,
            using_ems: false,
            done_retry: false,
            send_tickets: 0,
        }
    }

    /// Continues handling of a `ClientHello` message once config and certificate are available.
    pub(super) fn with_input(
        self,
        input: ClientHelloInput<'_>,
        output: &mut dyn Output<'_>,
    ) -> Result<ServerState, Error> {
        let tls13_enabled = self
            .config
            .supports_version(ProtocolVersion::TLSv1_3);
        let tls12_enabled = self
            .config
            .supports_version(ProtocolVersion::TLSv1_2);

        // Are we doing TLS1.3?
        if let Some(versions) = &input.client_hello.supported_versions {
            if versions.tls13 && tls13_enabled {
                self.with_version::<Tls13CipherSuite>(input, output)
            } else if !versions.tls12 || !tls12_enabled {
                Err(PeerIncompatible::Tls12NotOfferedOrEnabled.into())
            } else if self.protocol.is_quic() {
                Err(PeerIncompatible::Tls13RequiredForQuic.into())
            } else {
                self.with_version::<Tls12CipherSuite>(input, output)
            }
        } else if u16::from(input.client_hello.client_version) < u16::from(ProtocolVersion::TLSv1_2)
        {
            Err(PeerIncompatible::Tls12NotOffered.into())
        } else if !tls12_enabled && tls13_enabled {
            Err(PeerIncompatible::SupportedVersionsExtensionRequired.into())
        } else if self.protocol.is_quic() {
            Err(PeerIncompatible::Tls13RequiredForQuic.into())
        } else {
            self.with_version::<Tls12CipherSuite>(input, output)
        }
    }

    fn with_version<T: Suite + 'static>(
        mut self,
        input: ClientHelloInput<'_>,
        output: &mut dyn Output<'_>,
    ) -> Result<ServerState, Error>
    where
        CryptoProvider: Borrow<[&'static T]>,
        SupportedCipherSuite: From<&'static T>,
        dyn CipherSuiteSelector: VersionSuiteSelector<T>,
    {
        output.output(OutputEvent::ProtocolVersion(T::VERSION));

        let sni = self
            .config
            .invalid_sni_policy
            .accept(input.client_hello.server_name.as_ref())?;
        output.emit(Event::ReceivedServerName(sni.clone()));

        if self.done_retry {
            let ch_sni = input
                .client_hello
                .server_name
                .as_ref()
                .and_then(ServerNamePayload::to_dns_name_normalized);
            if self.sni != ch_sni {
                return Err(PeerMisbehaved::ServerNameDifferedOnRetry.into());
            }
        }

        // We communicate to the upper layer what kind of key they should choose
        // via the sigschemes value.  Clients tend to treat this extension
        // orthogonally to offered ciphersuites (even though, in TLS1.2 it is not).
        // So: reduce the offered sigschemes to those compatible with the
        // intersection of ciphersuites.
        let suites = <CryptoProvider as Borrow<[&'static T]>>::borrow(&self.config.provider);
        let client_suites = suites
            .iter()
            .filter(|&&scs| {
                input
                    .client_hello
                    .cipher_suites
                    .contains(&scs.suite())
            })
            .collect::<Vec<_>>();

        let mut sig_schemes = input.sig_schemes.to_owned();
        if T::VERSION == ProtocolVersion::TLSv1_2 {
            sig_schemes.retain(|scheme| {
                client_suites
                    .iter()
                    .any(|&suite| suite.usable_for_signature_scheme(*scheme))
            });
        } else if T::VERSION == ProtocolVersion::TLSv1_3 {
            sig_schemes.retain(SignatureScheme::supported_in_tls13);
        }

        // Choose a certificate.
        let credentials = self
            .config
            .cert_resolver
            .resolve(&ClientHello::new(
                input.client_hello,
                Some(&sig_schemes),
                sni.as_ref().map(Cow::Borrowed),
                Some(T::VERSION),
            ))?;
        self.sni = sni;

        let (suite, skxg) = self.choose_suite_and_kx_group(
            suites,
            credentials.signer.scheme(),
            input
                .client_hello
                .named_groups
                .as_deref()
                .unwrap_or_default(),
            &input.client_hello.cipher_suites,
        )?;

        debug!("decided upon suite {suite:?}");
        output.output(OutputEvent::CipherSuite(suite.into()));

        suite
            .server_handler()
            .handle_client_hello(suite, skxg, credentials, input, self, output)
    }

    fn choose_suite_and_kx_group<T: Suite + 'static>(
        &self,
        suites: &[&'static T],
        sig_scheme: SignatureScheme,
        client_groups: &[NamedGroup],
        client_suites: &[CipherSuite],
    ) -> Result<(&'static T, &'static dyn SupportedKxGroup), PeerIncompatible>
    where
        SupportedCipherSuite: From<&'static T>,
        dyn CipherSuiteSelector: VersionSuiteSelector<T>,
    {
        // Determine which `KeyExchangeAlgorithm`s are theoretically possible, based
        // on the offered and supported groups.
        let mut ecdhe_possible = false;
        let mut ffdhe_possible = false;
        let mut ffdhe_offered = false;
        let mut supported_groups: Vec<&'static dyn SupportedKxGroup> =
            Vec::with_capacity(client_groups.len());

        for offered_group in client_groups {
            let supported = self
                .config
                .provider
                .find_kx_group(*offered_group, T::VERSION);

            match offered_group.key_exchange_algorithm() {
                KeyExchangeAlgorithm::DHE => {
                    ffdhe_possible |= supported.is_some();
                    ffdhe_offered = true;
                }
                KeyExchangeAlgorithm::ECDHE => {
                    ecdhe_possible |= supported.is_some();
                }
            }

            if let Some(supported) = supported {
                supported_groups.push(supported);
            }
        }

        let first_supported_dhe_kxg = if T::VERSION == ProtocolVersion::TLSv1_2 {
            // https://datatracker.ietf.org/doc/html/rfc7919#section-4 (paragraph 2)
            let first_supported_dhe_kxg = self
                .config
                .provider
                .kx_groups
                .iter()
                .find(|skxg| skxg.name().key_exchange_algorithm() == KeyExchangeAlgorithm::DHE);
            ffdhe_possible |= !ffdhe_offered && first_supported_dhe_kxg.is_some();
            first_supported_dhe_kxg
        } else {
            // In TLS1.3, the server may only directly negotiate a group.
            None
        };

        if !ecdhe_possible && !ffdhe_possible {
            return Err(PeerIncompatible::NoKxGroupsInCommon);
        }

        // RFC 7919 (https://datatracker.ietf.org/doc/html/rfc7919#section-4) requires us to send
        // the InsufficientSecurity alert in case we don't recognize client's FFDHE groups (i.e.,
        // `suitable_suites` becomes empty). But that does not make a lot of sense (e.g., client
        // proposes FFDHE4096 and we only support FFDHE2048), so we ignore that requirement here,
        // and continue to send HandshakeFailure.

        let mut client_suites = client_suites
            .iter()
            .filter_map(|&suite| {
                let &suite = suites
                    .iter()
                    .find(|ss| ss.suite() == suite)?;

                // Reduce our supported ciphersuites by the certified key's algorithm.
                (suite.usable_for_signature_scheme(sig_scheme)
                // And support for one of the key exchange groups
                && (ecdhe_possible && suite.usable_for_kx_algorithm(KeyExchangeAlgorithm::ECDHE)
                || ffdhe_possible && suite.usable_for_kx_algorithm(KeyExchangeAlgorithm::DHE)))
                .then_some(suite)
            });

        let suite = self
            .config
            .cipher_suite_selector
            .select(&mut client_suites, suites)
            .ok_or(PeerIncompatible::NoCipherSuitesInCommon)?;

        // Finally, choose a key exchange group that is compatible with the selected cipher
        // suite.
        let maybe_skxg = supported_groups
            .iter()
            .find(|kx_group| {
                suite.usable_for_kx_algorithm(kx_group.name().key_exchange_algorithm())
            });

        if T::VERSION == ProtocolVersion::TLSv1_3 {
            // This unwrap is structurally guaranteed by the early return for `!ffdhe_possible && !ecdhe_possible`
            return Ok((suite, *maybe_skxg.unwrap()));
        }

        // For TLS1.2, the server can unilaterally choose a DHE group if it has one and
        // there was no better option.
        match maybe_skxg {
            Some(skxg) => Ok((suite, *skxg)),
            None if suite.usable_for_kx_algorithm(KeyExchangeAlgorithm::DHE) => {
                // If kx for the selected cipher suite is DHE and no DHE groups are specified in the extension,
                // the server is free to choose DHE params, we choose the first DHE kx group of the provider.
                if let Some(server_selected_ffdhe_skxg) = first_supported_dhe_kxg {
                    Ok((suite, *server_selected_ffdhe_skxg))
                } else {
                    Err(PeerIncompatible::NoKxGroupsInCommon)
                }
            }
            None => Err(PeerIncompatible::NoKxGroupsInCommon),
        }
    }

    pub(super) fn randoms(&self, input: &ClientHelloInput<'_>) -> Result<ConnectionRandoms, Error> {
        Ok(ConnectionRandoms::new(
            input.client_hello.random,
            Random::new(self.config.provider.secure_random)?,
        ))
    }
}

impl ExpectClientHello {
    pub(crate) fn handle<'m>(
        self,
        input: Input<'m>,
        output: &mut dyn Output<'_>,
    ) -> Result<ServerState, Error> {
        let input = ClientHelloInput::from_input(&input)?;
        self.with_input(input, output)
    }

    fn set_resumption_data(&mut self, resumption_data: &[u8]) -> Result<(), Error> {
        self.resumption_data = resumption_data.to_vec();
        Ok(())
    }
}

impl From<Box<ExpectClientHello>> for ServerState {
    fn from(value: Box<ExpectClientHello>) -> Self {
        Self::ClientHello(value)
    }
}

pub(crate) trait ServerHandler<T>: fmt::Debug + Sealed + Send + Sync {
    fn handle_client_hello(
        &self,
        suite: &'static T,
        kx_group: &'static dyn SupportedKxGroup,
        credentials: SelectedCredential,
        input: ClientHelloInput<'_>,
        st: ExpectClientHello,
        output: &mut dyn Output<'_>,
    ) -> Result<ServerState, Error>;
}

pub(crate) struct ClientHelloInput<'a> {
    pub(super) message: &'a Message<'a>,
    pub(super) client_hello: &'a ClientHelloPayload,
    pub(super) sig_schemes: &'a [SignatureScheme],
    pub(super) proof: HandshakeAlignedProof,
}

impl<'a> ClientHelloInput<'a> {
    /// Configuration-independent validation of a `ClientHello` message.
    ///
    /// This represents the first part of the `ClientHello` handling, where we do all validation that
    /// doesn't depend on a `ServerConfig` being available and extract everything needed to build a
    /// [`ClientHello`] value for a [`ServerCredentialResolver`].
    ///
    /// [`ServerCredentialResolver`]: crate::server::ServerCredentialResolver
    pub(super) fn from_input(input: &'a Input<'a>) -> Result<Self, Error> {
        let client_hello = require_handshake_msg!(
            input.message,
            HandshakeType::ClientHello,
            HandshakePayload::ClientHello
        )?;
        trace!("we got a clienthello {client_hello:?}");

        if !client_hello
            .compression_methods
            .contains(&Compression::Null)
        {
            return Err(PeerIncompatible::NullCompressionRequired.into());
        }

        // No handshake messages should follow this one in this flight.
        let proof = input.check_aligned_handshake()?;

        let sig_schemes = client_hello
            .signature_schemes
            .as_deref()
            .ok_or(PeerIncompatible::SignatureAlgorithmsExtensionRequired)?;

        Ok(ClientHelloInput {
            message: &input.message,
            client_hello,
            sig_schemes,
            proof,
        })
    }
}

pub(crate) enum HandshakeHashOrBuffer {
    Buffer(HandshakeHashBuffer),
    Hash(HandshakeHash),
}

impl HandshakeHashOrBuffer {
    pub(super) fn start(self, hash: &'static dyn Hash) -> Result<HandshakeHash, Error> {
        match self {
            Self::Buffer(inner) => Ok(inner.start_hash(hash)),
            Self::Hash(inner) if inner.algorithm() == hash.algorithm() => Ok(inner),
            _ => Err(PeerMisbehaved::HandshakeHashVariedAfterRetry.into()),
        }
    }
}