Coverage Report

Created: 2026-10-28 06:24

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rustls-0.23.46/src/server/hs.rs
Line
Count
Source
1
use alloc::borrow::ToOwned;
2
use alloc::boxed::Box;
3
use alloc::vec::Vec;
4
5
use pki_types::DnsName;
6
7
use super::server_conn::ServerConnectionData;
8
#[cfg(feature = "tls12")]
9
use super::tls12;
10
use crate::common_state::{KxState, Protocol, State};
11
use crate::conn::ConnectionRandoms;
12
use crate::crypto::SupportedKxGroup;
13
use crate::enums::{
14
    AlertDescription, CertificateType, CipherSuite, HandshakeType, ProtocolVersion,
15
    SignatureAlgorithm, SignatureScheme,
16
};
17
use crate::error::{Error, PeerIncompatible, PeerMisbehaved};
18
use crate::hash_hs::{HandshakeHash, HandshakeHashBuffer};
19
use crate::log::{debug, trace};
20
use crate::msgs::enums::{Compression, ExtensionType, NamedGroup};
21
#[cfg(feature = "tls12")]
22
use crate::msgs::handshake::SessionId;
23
use crate::msgs::handshake::{
24
    ClientHelloPayload, HandshakePayload, KeyExchangeAlgorithm, ProtocolName, Random,
25
    ServerExtensions, ServerExtensionsInput, ServerNamePayload, SingleProtocolName,
26
    TransportParameters,
27
};
28
use crate::msgs::message::{Message, MessagePayload};
29
use crate::msgs::persist;
30
use crate::server::common::ActiveCertifiedKey;
31
use crate::server::{ClientHello, ServerConfig, tls13};
32
use crate::sync::Arc;
33
use crate::{SupportedCipherSuite, suites};
34
35
pub(super) type NextState<'a> = Box<dyn State<ServerConnectionData> + 'a>;
36
pub(super) type NextStateOrError<'a> = Result<NextState<'a>, Error>;
37
pub(super) type ServerContext<'a> = crate::common_state::Context<'a, ServerConnectionData>;
38
39
0
pub(super) fn can_resume(
40
0
    suite: SupportedCipherSuite,
41
0
    sni: &Option<DnsName<'_>>,
42
0
    using_ems: bool,
43
0
    resumedata: &persist::ServerSessionValue,
44
0
) -> bool {
45
    // The RFCs underspecify what happens if we try to resume to
46
    // an unoffered/varying suite.  We merely don't resume in weird cases.
47
    //
48
    // RFC 6066 says "A server that implements this extension MUST NOT accept
49
    // the request to resume the session if the server_name extension contains
50
    // a different name. Instead, it proceeds with a full handshake to
51
    // establish a new session."
52
    //
53
    // RFC 8446: "The server MUST ensure that it selects
54
    // a compatible PSK (if any) and cipher suite."
55
0
    resumedata.cipher_suite == suite.suite()
56
0
        && (resumedata.extended_ms == using_ems || (resumedata.extended_ms && !using_ems))
57
0
        && &resumedata.sni == sni
58
0
}
Unexecuted instantiation: rustls::server::hs::can_resume
Unexecuted instantiation: rustls::server::hs::can_resume
Unexecuted instantiation: rustls::server::hs::can_resume
59
60
#[derive(Default)]
61
pub(super) struct ExtensionProcessing {
62
    // extensions to reply with
63
    pub(super) extensions: Box<ServerExtensions<'static>>,
64
    #[cfg(feature = "tls12")]
65
    pub(super) send_ticket: bool,
66
}
67
68
impl ExtensionProcessing {
69
0
    pub(super) fn new(extra_exts: ServerExtensionsInput<'static>) -> Self {
70
        let ServerExtensionsInput {
71
0
            transport_parameters,
72
0
        } = extra_exts;
73
74
0
        let mut extensions = Box::new(ServerExtensions::default());
75
0
        match transport_parameters {
76
0
            Some(TransportParameters::Quic(v)) => extensions.transport_parameters = Some(v),
77
0
            Some(TransportParameters::QuicDraft(v)) => {
78
0
                extensions.transport_parameters_draft = Some(v)
79
            }
80
0
            None => {}
81
        }
82
83
0
        Self {
84
0
            extensions,
85
0
            #[cfg(feature = "tls12")]
86
0
            send_ticket: false,
87
0
        }
88
0
    }
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::new
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::new
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::new
89
90
0
    pub(super) fn process_common(
91
0
        &mut self,
92
0
        config: &ServerConfig,
93
0
        cx: &mut ServerContext<'_>,
94
0
        ocsp_response: &mut Option<&[u8]>,
95
0
        hello: &ClientHelloPayload,
96
0
        resumedata: Option<&persist::ServerSessionValue>,
97
0
    ) -> Result<(), Error> {
98
        // ALPN
99
0
        let our_protocols = &config.alpn_protocols;
100
0
        if let Some(their_protocols) = &hello.protocols {
101
0
            cx.common.alpn_protocol = our_protocols
102
0
                .iter()
103
0
                .find(|ours| {
104
0
                    their_protocols
105
0
                        .iter()
106
0
                        .any(|theirs| theirs.as_ref() == ours.as_slice())
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common::{closure#0}::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common::{closure#0}::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common::{closure#0}::{closure#0}
107
0
                })
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common::{closure#0}
108
0
                .map(|bytes| ProtocolName::from(bytes.clone()));
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common::{closure#1}
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common::{closure#1}
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common::{closure#1}
109
0
            if let Some(selected_protocol) = &cx.common.alpn_protocol {
110
0
                debug!("Chosen ALPN protocol {selected_protocol:?}");
111
0
112
0
                self.extensions.selected_protocol =
113
0
                    Some(SingleProtocolName::new(selected_protocol.clone()));
114
0
            } else if !our_protocols.is_empty() {
115
0
                return Err(cx.common.send_fatal_alert(
116
0
                    AlertDescription::NoApplicationProtocol,
117
0
                    Error::NoApplicationProtocol,
118
0
                ));
119
0
            }
120
0
        }
121
122
0
        if cx.common.is_quic() {
123
            // QUIC has strict ALPN, unlike TLS's more backwards-compatible behavior. RFC 9001
124
            // says: "The server MUST treat the inability to select a compatible application
125
            // protocol as a connection error of type 0x0178". We judge that ALPN was desired
126
            // (rather than some out-of-band protocol negotiation mechanism) if and only if any ALPN
127
            // protocols were configured locally or offered by the client. This helps prevent
128
            // successful establishment of connections between peers that can't understand
129
            // each other.
130
0
            if cx.common.alpn_protocol.is_none()
131
0
                && (!our_protocols.is_empty() || hello.protocols.is_some())
132
            {
133
0
                return Err(cx.common.send_fatal_alert(
134
0
                    AlertDescription::NoApplicationProtocol,
135
0
                    Error::NoApplicationProtocol,
136
0
                ));
137
0
            }
138
139
0
            let transport_params = hello
140
0
                .transport_parameters
141
0
                .as_ref()
142
0
                .or(hello
143
0
                    .transport_parameters_draft
144
0
                    .as_ref());
145
0
            match transport_params {
146
0
                Some(params) => cx.common.quic.params = Some(params.to_owned().into_vec()),
147
                None => {
148
0
                    return Err(cx
149
0
                        .common
150
0
                        .missing_extension(PeerMisbehaved::MissingQuicTransportParameters));
151
                }
152
            }
153
0
        }
154
155
0
        let for_resume = resumedata.is_some();
156
        // SNI
157
0
        if let (false, Some(ServerNamePayload::SingleDnsName(_))) = (for_resume, &hello.server_name)
158
0
        {
159
0
            self.extensions.server_name_ack = Some(());
160
0
        }
161
162
        // Send status_request response if we have one.  This is not allowed
163
        // if we're resuming, and is only triggered if we have an OCSP response
164
        // to send.
165
0
        if !for_resume
166
0
            && hello
167
0
                .certificate_status_request
168
0
                .is_some()
169
        {
170
0
            if ocsp_response.is_some() && !cx.common.is_tls13() {
171
0
                // Only TLS1.2 sends confirmation in ServerHello
172
0
                self.extensions
173
0
                    .certificate_status_request_ack = Some(());
174
0
            }
175
0
        } else {
176
0
            // Throw away any OCSP response so we don't try to send it later.
177
0
            ocsp_response.take();
178
0
        }
179
180
0
        self.validate_server_cert_type_extension(hello, config, cx)?;
181
0
        self.validate_client_cert_type_extension(hello, config, cx)?;
182
183
0
        Ok(())
184
0
    }
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_common
185
186
    #[cfg(feature = "tls12")]
187
    pub(super) fn process_tls12(
188
        &mut self,
189
        config: &ServerConfig,
190
        hello: &ClientHelloPayload,
191
        using_ems: bool,
192
    ) {
193
        // Renegotiation.
194
        // (We don't do reneg at all, but would support the secure version if we did.)
195
196
        use crate::msgs::base::PayloadU8;
197
        let secure_reneg_offered = hello.renegotiation_info.is_some()
198
            || hello
199
                .cipher_suites
200
                .contains(&CipherSuite::TLS_EMPTY_RENEGOTIATION_INFO_SCSV);
201
202
        if secure_reneg_offered {
203
            self.extensions.renegotiation_info = Some(PayloadU8::new(Vec::new()));
204
        }
205
206
        // Tickets:
207
        // If we get any SessionTicket extension and have tickets enabled,
208
        // we send an ack.
209
        if hello.session_ticket.is_some() && config.ticketer.enabled() {
210
            self.send_ticket = true;
211
            self.extensions.session_ticket_ack = Some(());
212
        }
213
214
        // Confirm use of EMS if offered.
215
        if using_ems {
216
            self.extensions
217
                .extended_master_secret_ack = Some(());
218
        }
219
    }
220
221
0
    fn validate_server_cert_type_extension(
222
0
        &mut self,
223
0
        hello: &ClientHelloPayload,
224
0
        config: &ServerConfig,
225
0
        cx: &mut ServerContext<'_>,
226
0
    ) -> Result<(), Error> {
227
0
        let client_supports = hello
228
0
            .server_certificate_types
229
0
            .as_deref()
230
0
            .unwrap_or_default();
231
232
0
        self.process_cert_type_extension(
233
0
            client_supports,
234
0
            config
235
0
                .cert_resolver
236
0
                .only_raw_public_keys(),
237
0
            ExtensionType::ServerCertificateType,
238
0
            cx,
239
        )
240
0
    }
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::validate_server_cert_type_extension
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::validate_server_cert_type_extension
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::validate_server_cert_type_extension
241
242
0
    fn validate_client_cert_type_extension(
243
0
        &mut self,
244
0
        hello: &ClientHelloPayload,
245
0
        config: &ServerConfig,
246
0
        cx: &mut ServerContext<'_>,
247
0
    ) -> Result<(), Error> {
248
0
        let client_supports = hello
249
0
            .client_certificate_types
250
0
            .as_deref()
251
0
            .unwrap_or_default();
252
253
0
        self.process_cert_type_extension(
254
0
            client_supports,
255
0
            config
256
0
                .verifier
257
0
                .requires_raw_public_keys(),
258
0
            ExtensionType::ClientCertificateType,
259
0
            cx,
260
        )
261
0
    }
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::validate_client_cert_type_extension
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::validate_client_cert_type_extension
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::validate_client_cert_type_extension
262
263
0
    fn process_cert_type_extension(
264
0
        &mut self,
265
0
        client_supports: &[CertificateType],
266
0
        requires_raw_keys: bool,
267
0
        extension_type: ExtensionType,
268
0
        cx: &mut ServerContext<'_>,
269
0
    ) -> Result<(), Error> {
270
0
        debug_assert!(
271
0
            extension_type == ExtensionType::ClientCertificateType
272
0
                || extension_type == ExtensionType::ServerCertificateType
273
        );
274
0
        let raw_key_negotation_result = match (
275
0
            requires_raw_keys,
276
0
            client_supports.contains(&CertificateType::RawPublicKey),
277
0
            client_supports.contains(&CertificateType::X509),
278
0
        ) {
279
0
            (true, true, _) => Ok((extension_type, CertificateType::RawPublicKey)),
280
0
            (false, _, true) => Ok((extension_type, CertificateType::X509)),
281
0
            (false, true, false) => Err(Error::PeerIncompatible(
282
0
                PeerIncompatible::IncorrectCertificateTypeExtension,
283
0
            )),
284
0
            (true, false, _) => Err(Error::PeerIncompatible(
285
0
                PeerIncompatible::IncorrectCertificateTypeExtension,
286
0
            )),
287
0
            (false, false, false) => return Ok(()),
288
        };
289
290
0
        match raw_key_negotation_result {
291
0
            Ok((ExtensionType::ClientCertificateType, cert_type)) => {
292
0
                self.extensions.client_certificate_type = Some(cert_type);
293
0
            }
294
0
            Ok((ExtensionType::ServerCertificateType, cert_type)) => {
295
0
                self.extensions.server_certificate_type = Some(cert_type);
296
0
            }
297
0
            Err(err) => {
298
0
                return Err(cx
299
0
                    .common
300
0
                    .send_fatal_alert(AlertDescription::HandshakeFailure, err));
301
            }
302
0
            Ok((_, _)) => unreachable!(),
303
        }
304
0
        Ok(())
305
0
    }
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_cert_type_extension
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_cert_type_extension
Unexecuted instantiation: <rustls::server::hs::ExtensionProcessing>::process_cert_type_extension
306
}
307
308
pub(super) struct ExpectClientHello {
309
    pub(super) config: Arc<ServerConfig>,
310
    pub(super) extra_exts: ServerExtensionsInput<'static>,
311
    pub(super) transcript: HandshakeHashOrBuffer,
312
    #[cfg(feature = "tls12")]
313
    pub(super) session_id: SessionId,
314
    #[cfg(feature = "tls12")]
315
    pub(super) using_ems: bool,
316
    pub(super) previous_hello: Option<PreviousClientHello>,
317
    pub(super) send_tickets: usize,
318
}
319
320
impl ExpectClientHello {
321
0
    pub(super) fn new(
322
0
        config: Arc<ServerConfig>,
323
0
        extra_exts: ServerExtensionsInput<'static>,
324
0
    ) -> Self {
325
0
        let mut transcript_buffer = HandshakeHashBuffer::new();
326
327
0
        if config.verifier.offer_client_auth() {
328
0
            transcript_buffer.set_client_auth_enabled();
329
0
        }
330
331
0
        Self {
332
0
            config,
333
0
            extra_exts,
334
0
            transcript: HandshakeHashOrBuffer::Buffer(transcript_buffer),
335
0
            #[cfg(feature = "tls12")]
336
0
            session_id: SessionId::empty(),
337
0
            #[cfg(feature = "tls12")]
338
0
            using_ems: false,
339
0
            previous_hello: None,
340
0
            send_tickets: 0,
341
0
        }
342
0
    }
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::new
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::new
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::new
343
344
    /// Continues handling of a `ClientHello` message once config and certificate are available.
345
0
    pub(super) fn with_certified_key(
346
0
        self,
347
0
        mut sig_schemes: Vec<SignatureScheme>,
348
0
        client_hello: &ClientHelloPayload,
349
0
        m: &Message<'_>,
350
0
        cx: &mut ServerContext<'_>,
351
0
    ) -> NextStateOrError<'static> {
352
0
        let tls13_enabled = self
353
0
            .config
354
0
            .supports_version(ProtocolVersion::TLSv1_3, cx.common.protocol);
355
0
        let tls12_enabled = self
356
0
            .config
357
0
            .supports_version(ProtocolVersion::TLSv1_2, cx.common.protocol)
358
0
            && !self.previous_hello.is_some();
359
360
        // Are we doing TLS1.3?
361
0
        let version = if let Some(versions) = &client_hello.supported_versions {
362
0
            if versions.tls13 && tls13_enabled {
363
0
                ProtocolVersion::TLSv1_3
364
0
            } else if !versions.tls12 || !tls12_enabled {
365
0
                return Err(cx.common.send_fatal_alert(
366
0
                    AlertDescription::ProtocolVersion,
367
0
                    PeerIncompatible::Tls12NotOfferedOrEnabled,
368
0
                ));
369
0
            } else if cx.common.is_quic() {
370
0
                return Err(cx.common.send_fatal_alert(
371
0
                    AlertDescription::ProtocolVersion,
372
0
                    PeerIncompatible::Tls13RequiredForQuic,
373
0
                ));
374
            } else {
375
0
                ProtocolVersion::TLSv1_2
376
            }
377
0
        } else if u16::from(client_hello.client_version) < u16::from(ProtocolVersion::TLSv1_2) {
378
0
            return Err(cx.common.send_fatal_alert(
379
0
                AlertDescription::ProtocolVersion,
380
0
                PeerIncompatible::Tls12NotOffered,
381
0
            ));
382
0
        } else if cx.common.is_quic() {
383
0
            return Err(cx.common.send_fatal_alert(
384
0
                AlertDescription::ProtocolVersion,
385
0
                PeerIncompatible::Tls13RequiredForQuic,
386
0
            ));
387
0
        } else if !tls12_enabled && tls13_enabled {
388
0
            return Err(cx.common.send_fatal_alert(
389
0
                AlertDescription::ProtocolVersion,
390
0
                PeerIncompatible::SupportedVersionsExtensionRequired,
391
0
            ));
392
        } else {
393
0
            ProtocolVersion::TLSv1_2
394
        };
395
396
0
        cx.common.negotiated_version = Some(version);
397
398
        // We communicate to the upper layer what kind of key they should choose
399
        // via the sigschemes value.  Clients tend to treat this extension
400
        // orthogonally to offered ciphersuites (even though, in TLS1.2 it is not).
401
        // So: reduce the offered sigschemes to those compatible with the
402
        // intersection of ciphersuites.
403
0
        let client_suites = self
404
0
            .config
405
0
            .provider
406
0
            .cipher_suites
407
0
            .iter()
408
0
            .copied()
409
0
            .filter(|scs| {
410
0
                client_hello
411
0
                    .cipher_suites
412
0
                    .contains(&scs.suite())
413
0
            })
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#0}
414
0
            .collect::<Vec<_>>();
415
416
0
        sig_schemes
417
0
            .retain(|scheme| suites::compatible_sigscheme_for_suites(*scheme, &client_suites));
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#1}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#1}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#1}
418
419
        // We adhere to the TLS 1.2 RFC by not exposing this to the cert resolver if TLS version is 1.2
420
0
        let certificate_authorities = match version {
421
0
            ProtocolVersion::TLSv1_2 => None,
422
0
            _ => client_hello
423
0
                .certificate_authority_names
424
0
                .as_deref(),
425
        };
426
        // Choose a certificate.
427
0
        let certkey = {
428
0
            let client_hello = ClientHello {
429
0
                server_name: &cx.data.sni,
430
0
                signature_schemes: &sig_schemes,
431
0
                alpn: client_hello.protocols.as_ref(),
432
0
                client_cert_types: client_hello
433
0
                    .client_certificate_types
434
0
                    .as_deref(),
435
0
                server_cert_types: client_hello
436
0
                    .server_certificate_types
437
0
                    .as_deref(),
438
0
                cipher_suites: &client_hello.cipher_suites,
439
0
                certificate_authorities,
440
0
                named_groups: client_hello.named_groups.as_deref(),
441
0
            };
442
0
            trace!("Resolving server certificate: {client_hello:#?}");
443
444
0
            let certkey = self
445
0
                .config
446
0
                .cert_resolver
447
0
                .resolve(client_hello);
448
449
0
            certkey.ok_or_else(|| {
450
0
                cx.common.send_fatal_alert(
451
0
                    AlertDescription::AccessDenied,
452
0
                    Error::General("no server certificate chain resolved".to_owned()),
453
                )
454
0
            })?
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#2}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#2}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#2}
455
        };
456
0
        let certkey = ActiveCertifiedKey::from_certified_key(&certkey);
457
458
0
        let (suite, skxg) = self
459
0
            .choose_suite_and_kx_group(
460
0
                version,
461
0
                certkey.get_key().algorithm(),
462
0
                cx.common.protocol,
463
0
                client_hello
464
0
                    .named_groups
465
0
                    .as_deref()
466
0
                    .unwrap_or_default(),
467
0
                &client_hello.cipher_suites,
468
            )
469
0
            .map_err(|incompat| {
470
0
                cx.common
471
0
                    .send_fatal_alert(AlertDescription::HandshakeFailure, incompat)
472
0
            })?;
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#3}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#3}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key::{closure#3}
473
474
        // RFC 9846 section 4.2.4: the server must negotiate the same cipher suite it
475
        // named in its HelloRetryRequest
476
        if let Some(PreviousClientHello {
477
0
            suite: before_retry,
478
            ..
479
0
        }) = self.previous_hello
480
        {
481
0
            if before_retry != suite.suite() {
482
0
                return Err(cx.common.send_fatal_alert(
483
0
                    AlertDescription::IllegalParameter,
484
0
                    PeerMisbehaved::CipherSuiteDifferedOnRetry,
485
0
                ));
486
0
            }
487
0
        }
488
489
0
        debug!("decided upon suite {suite:?}");
490
0
        cx.common.suite = Some(suite);
491
0
        cx.common.kx_state = KxState::Start(skxg);
492
493
        // Start handshake hash.
494
0
        let starting_hash = suite.hash_provider();
495
0
        let transcript = match self.transcript {
496
0
            HandshakeHashOrBuffer::Buffer(inner) => inner.start_hash(starting_hash),
497
0
            HandshakeHashOrBuffer::Hash(inner)
498
0
                if inner.algorithm() == starting_hash.algorithm() =>
499
            {
500
0
                inner
501
            }
502
            _ => {
503
0
                return Err(cx.common.send_fatal_alert(
504
0
                    AlertDescription::IllegalParameter,
505
0
                    PeerMisbehaved::HandshakeHashVariedAfterRetry,
506
0
                ));
507
            }
508
        };
509
510
        // Save their Random.
511
0
        let randoms = ConnectionRandoms::new(
512
0
            client_hello.random,
513
0
            Random::new(self.config.provider.secure_random)?,
514
        );
515
0
        match suite {
516
0
            SupportedCipherSuite::Tls13(suite) => tls13::CompleteClientHelloHandling {
517
0
                config: self.config,
518
0
                transcript,
519
0
                suite,
520
0
                randoms,
521
0
                previous_hello: self.previous_hello,
522
0
                send_tickets: self.send_tickets,
523
0
                extra_exts: self.extra_exts,
524
0
            }
525
0
            .handle_client_hello(cx, certkey, m, client_hello, skxg, sig_schemes),
526
            #[cfg(feature = "tls12")]
527
            SupportedCipherSuite::Tls12(suite) => tls12::CompleteClientHelloHandling {
528
                config: self.config,
529
                transcript,
530
                session_id: self.session_id,
531
                suite,
532
                using_ems: self.using_ems,
533
                randoms,
534
                send_ticket: self.send_tickets > 0,
535
                extra_exts: self.extra_exts,
536
            }
537
            .handle_client_hello(
538
                cx,
539
                certkey,
540
                m,
541
                client_hello,
542
                skxg,
543
                sig_schemes,
544
                tls13_enabled,
545
            ),
546
        }
547
0
    }
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::with_certified_key
548
549
0
    fn choose_suite_and_kx_group(
550
0
        &self,
551
0
        selected_version: ProtocolVersion,
552
0
        sig_key_algorithm: SignatureAlgorithm,
553
0
        protocol: Protocol,
554
0
        client_groups: &[NamedGroup],
555
0
        client_suites: &[CipherSuite],
556
0
    ) -> Result<(SupportedCipherSuite, &'static dyn SupportedKxGroup), PeerIncompatible> {
557
        // Determine which `KeyExchangeAlgorithm`s are theoretically possible, based
558
        // on the offered and supported groups.
559
0
        let mut ecdhe_possible = false;
560
0
        let mut ffdhe_possible = false;
561
0
        let mut ffdhe_offered = false;
562
0
        let mut supported_groups = Vec::with_capacity(client_groups.len());
563
564
0
        for offered_group in client_groups {
565
0
            let supported = self
566
0
                .config
567
0
                .provider
568
0
                .kx_groups
569
0
                .iter()
570
0
                .find(|skxg| {
571
0
                    skxg.usable_for_version(selected_version) && skxg.name() == *offered_group
572
0
                });
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#0}
573
574
0
            match offered_group.key_exchange_algorithm() {
575
0
                KeyExchangeAlgorithm::DHE => {
576
0
                    ffdhe_possible |= supported.is_some();
577
0
                    ffdhe_offered = true;
578
0
                }
579
0
                KeyExchangeAlgorithm::ECDHE => {
580
0
                    ecdhe_possible |= supported.is_some();
581
0
                }
582
            }
583
584
0
            supported_groups.push(supported);
585
        }
586
587
0
        let first_supported_dhe_kxg = if selected_version == ProtocolVersion::TLSv1_2 {
588
            // https://datatracker.ietf.org/doc/html/rfc7919#section-4 (paragraph 2)
589
0
            let first_supported_dhe_kxg = self
590
0
                .config
591
0
                .provider
592
0
                .kx_groups
593
0
                .iter()
594
0
                .find(|skxg| skxg.name().key_exchange_algorithm() == KeyExchangeAlgorithm::DHE);
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#1}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#1}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#1}
595
0
            ffdhe_possible |= !ffdhe_offered && first_supported_dhe_kxg.is_some();
596
0
            first_supported_dhe_kxg
597
        } else {
598
            // In TLS1.3, the server may only directly negotiate a group.
599
0
            None
600
        };
601
602
0
        if !ecdhe_possible && !ffdhe_possible {
603
0
            return Err(PeerIncompatible::NoKxGroupsInCommon);
604
0
        }
605
606
0
        let mut suitable_suites_iter = self
607
0
            .config
608
0
            .provider
609
0
            .cipher_suites
610
0
            .iter()
611
0
            .filter(|suite| {
612
                // Reduce our supported ciphersuites by the certified key's algorithm.
613
0
                suite.usable_for_signature_algorithm(sig_key_algorithm)
614
                // And version
615
0
                && suite.version().version == selected_version
616
                // And protocol
617
0
                && suite.usable_for_protocol(protocol)
618
                // And support one of key exchange groups
619
0
                && (ecdhe_possible && suite.usable_for_kx_algorithm(KeyExchangeAlgorithm::ECDHE)
620
0
                || ffdhe_possible && suite.usable_for_kx_algorithm(KeyExchangeAlgorithm::DHE))
621
0
            });
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#2}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#2}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#2}
622
623
        // RFC 7919 (https://datatracker.ietf.org/doc/html/rfc7919#section-4) requires us to send
624
        // the InsufficientSecurity alert in case we don't recognize client's FFDHE groups (i.e.,
625
        // `suitable_suites` becomes empty). But that does not make a lot of sense (e.g., client
626
        // proposes FFDHE4096 and we only support FFDHE2048), so we ignore that requirement here,
627
        // and continue to send HandshakeFailure.
628
629
0
        let suite = if self.config.ignore_client_order {
630
0
            suitable_suites_iter.find(|suite| client_suites.contains(&suite.suite()))
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#3}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#3}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#3}
631
        } else {
632
0
            let suitable_suites = suitable_suites_iter.collect::<Vec<_>>();
633
0
            client_suites
634
0
                .iter()
635
0
                .find_map(|client_suite| {
636
0
                    suitable_suites
637
0
                        .iter()
638
0
                        .find(|x| *client_suite == x.suite())
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#4}::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#4}::{closure#0}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#4}::{closure#0}
639
0
                })
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#4}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#4}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#4}
640
0
                .copied()
641
        }
642
0
        .ok_or(PeerIncompatible::NoCipherSuitesInCommon)?;
643
644
        // Finally, choose a key exchange group that is compatible with the selected cipher
645
        // suite.
646
0
        let maybe_skxg = supported_groups
647
0
            .iter()
648
0
            .find_map(|maybe_skxg| match maybe_skxg {
649
0
                Some(skxg) => suite
650
0
                    .usable_for_kx_algorithm(skxg.name().key_exchange_algorithm())
651
0
                    .then_some(*skxg),
652
0
                None => None,
653
0
            });
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#5}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#5}
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group::{closure#5}
654
655
0
        if selected_version == ProtocolVersion::TLSv1_3 {
656
            // This unwrap is structurally guaranteed by the early return for `!ffdhe_possible && !ecdhe_possible`
657
0
            return Ok((*suite, *maybe_skxg.unwrap()));
658
0
        }
659
660
        // For TLS1.2, the server can unilaterally choose a DHE group if it has one and
661
        // there was no better option.
662
0
        match maybe_skxg {
663
0
            Some(skxg) => Ok((*suite, *skxg)),
664
0
            None if suite.usable_for_kx_algorithm(KeyExchangeAlgorithm::DHE) => {
665
                // If kx for the selected cipher suite is DHE and no DHE groups are specified in the extension,
666
                // the server is free to choose DHE params, we choose the first DHE kx group of the provider.
667
0
                if let Some(server_selected_ffdhe_skxg) = first_supported_dhe_kxg {
668
0
                    Ok((*suite, *server_selected_ffdhe_skxg))
669
                } else {
670
0
                    Err(PeerIncompatible::NoKxGroupsInCommon)
671
                }
672
            }
673
0
            None => Err(PeerIncompatible::NoKxGroupsInCommon),
674
        }
675
0
    }
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello>::choose_suite_and_kx_group
676
}
677
678
pub(super) struct PreviousClientHello {
679
    pub(super) offered_psk: bool,
680
    pub(super) suite: CipherSuite,
681
}
682
683
impl State<ServerConnectionData> for ExpectClientHello {
684
0
    fn handle<'m>(
685
0
        self: Box<Self>,
686
0
        cx: &mut ServerContext<'_>,
687
0
        m: Message<'m>,
688
0
    ) -> NextStateOrError<'m>
689
0
    where
690
0
        Self: 'm,
691
    {
692
0
        let (client_hello, sig_schemes) =
693
0
            process_client_hello(&m, self.previous_hello.is_some(), cx)?;
694
0
        self.with_certified_key(sig_schemes, client_hello, &m, cx)
695
0
    }
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello as rustls::common_state::State<rustls::server::server_conn::ServerConnectionData>>::handle
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello as rustls::common_state::State<rustls::server::server_conn::ServerConnectionData>>::handle
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello as rustls::common_state::State<rustls::server::server_conn::ServerConnectionData>>::handle
696
697
0
    fn into_owned(self: Box<Self>) -> NextState<'static> {
698
0
        self
699
0
    }
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello as rustls::common_state::State<rustls::server::server_conn::ServerConnectionData>>::into_owned
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello as rustls::common_state::State<rustls::server::server_conn::ServerConnectionData>>::into_owned
Unexecuted instantiation: <rustls::server::hs::ExpectClientHello as rustls::common_state::State<rustls::server::server_conn::ServerConnectionData>>::into_owned
700
}
701
702
/// Configuration-independent validation of a `ClientHello` message.
703
///
704
/// This represents the first part of the `ClientHello` handling, where we do all validation that
705
/// doesn't depend on a `ServerConfig` being available and extract everything needed to build a
706
/// [`ClientHello`] value for a [`ResolvesServerCert`].
707
///
708
/// Note that this will modify `data.sni` even if config or certificate resolution fail.
709
///
710
/// [`ResolvesServerCert`]: crate::server::ResolvesServerCert
711
0
pub(super) fn process_client_hello<'m>(
712
0
    m: &'m Message<'m>,
713
0
    done_retry: bool,
714
0
    cx: &mut ServerContext<'_>,
715
0
) -> Result<(&'m ClientHelloPayload, Vec<SignatureScheme>), Error> {
716
0
    let client_hello =
717
0
        require_handshake_msg!(m, HandshakeType::ClientHello, HandshakePayload::ClientHello)?;
718
0
    trace!("we got a clienthello {client_hello:?}");
719
720
0
    if !client_hello
721
0
        .compression_methods
722
0
        .contains(&Compression::Null)
723
    {
724
0
        return Err(cx.common.send_fatal_alert(
725
0
            AlertDescription::IllegalParameter,
726
0
            PeerIncompatible::NullCompressionRequired,
727
0
        ));
728
0
    }
729
730
    // No handshake messages should follow this one in this flight.
731
0
    cx.common.check_aligned_handshake()?;
732
733
    // Extract and validate the SNI DNS name, if any, before giving it to
734
    // the cert resolver. In particular, if it is invalid then we should
735
    // send an Illegal Parameter alert instead of the Internal Error alert
736
    // (or whatever) that we'd send if this were checked later or in a
737
    // different way.
738
    //
739
    // [RFC6066][] specifies that literal IP addresses are illegal in
740
    // `ServerName`s with a `name_type` of `host_name`.
741
    //
742
    // Some clients incorrectly send such extensions: we choose to
743
    // successfully parse these (into `ServerNamePayload::IpAddress`)
744
    // but then act like the client sent no `server_name` extension.
745
    //
746
    // [RFC6066]: https://datatracker.ietf.org/doc/html/rfc6066#section-3
747
0
    let sni = match &client_hello.server_name {
748
0
        Some(ServerNamePayload::SingleDnsName(dns_name)) => Some(dns_name.to_lowercase_owned()),
749
0
        Some(ServerNamePayload::IpAddress) => None,
750
        Some(ServerNamePayload::Invalid) => {
751
0
            return Err(cx.common.send_fatal_alert(
752
0
                AlertDescription::IllegalParameter,
753
0
                PeerMisbehaved::ServerNameMustContainOneHostName,
754
0
            ));
755
        }
756
0
        None => None,
757
    };
758
759
    // save only the first SNI
760
0
    if let (Some(sni), false) = (&sni, done_retry) {
761
        // Save the SNI into the session.
762
        // The SNI hostname is immutable once set.
763
0
        assert!(cx.data.sni.is_none());
764
0
        cx.data.sni = Some(sni.clone());
765
0
    } else if cx.data.sni != sni {
766
0
        return Err(PeerMisbehaved::ServerNameDifferedOnRetry.into());
767
0
    }
768
769
0
    let sig_schemes = client_hello
770
0
        .signature_schemes
771
0
        .as_ref()
772
0
        .ok_or_else(|| {
773
0
            cx.common.send_fatal_alert(
774
0
                AlertDescription::HandshakeFailure,
775
0
                PeerIncompatible::SignatureAlgorithmsExtensionRequired,
776
            )
777
0
        })?;
Unexecuted instantiation: rustls::server::hs::process_client_hello::{closure#0}
Unexecuted instantiation: rustls::server::hs::process_client_hello::{closure#0}
Unexecuted instantiation: rustls::server::hs::process_client_hello::{closure#0}
778
779
0
    Ok((client_hello, sig_schemes.to_owned()))
780
0
}
Unexecuted instantiation: rustls::server::hs::process_client_hello
Unexecuted instantiation: rustls::server::hs::process_client_hello
Unexecuted instantiation: rustls::server::hs::process_client_hello
781
782
pub(crate) enum HandshakeHashOrBuffer {
783
    Buffer(HandshakeHashBuffer),
784
    Hash(HandshakeHash),
785
}