Coverage Report

Created: 2026-07-30 06:46

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/rustls-0.23.43/src/server/tls13.rs
Line
Count
Source
1
use alloc::boxed::Box;
2
use alloc::vec;
3
use alloc::vec::Vec;
4
5
pub(super) use client_hello::CompleteClientHelloHandling;
6
use pki_types::{CertificateDer, UnixTime};
7
use subtle::ConstantTimeEq;
8
9
use super::hs::{self, HandshakeHashOrBuffer, ServerContext};
10
use super::server_conn::ServerConnectionData;
11
use crate::check::{inappropriate_handshake_message, inappropriate_message};
12
use crate::common_state::{
13
    CommonState, HandshakeFlightTls13, HandshakeKind, Protocol, Side, State,
14
};
15
use crate::conn::ConnectionRandoms;
16
use crate::conn::kernel::{Direction, KernelContext, KernelState};
17
use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion};
18
use crate::error::{Error, InvalidMessage, PeerIncompatible, PeerMisbehaved};
19
use crate::hash_hs::HandshakeHash;
20
use crate::log::{debug, trace, warn};
21
use crate::msgs::codec::{Codec, Reader};
22
use crate::msgs::enums::KeyUpdateRequest;
23
use crate::msgs::handshake::{
24
    CERTIFICATE_MAX_SIZE_LIMIT, CertificateChain, CertificatePayloadTls13, HandshakeMessagePayload,
25
    HandshakePayload, NewSessionTicketPayloadTls13,
26
};
27
use crate::msgs::message::{Message, MessagePayload};
28
use crate::msgs::persist;
29
use crate::server::ServerConfig;
30
use crate::suites::PartiallyExtractedSecrets;
31
use crate::sync::Arc;
32
use crate::tls13::key_schedule::{
33
    KeyScheduleResumption, KeyScheduleTraffic, KeyScheduleTrafficWithClientFinishedPending,
34
};
35
use crate::tls13::{
36
    Tls13CipherSuite, construct_client_verify_message, construct_server_verify_message,
37
};
38
use crate::{ConnectionTrafficSecrets, compress, rand, verify};
39
40
mod client_hello {
41
    use super::*;
42
    use crate::compress::CertCompressor;
43
    use crate::crypto::SupportedKxGroup;
44
    use crate::enums::SignatureScheme;
45
    use crate::msgs::base::{Payload, PayloadU8};
46
    use crate::msgs::ccs::ChangeCipherSpecPayload;
47
    use crate::msgs::enums::{Compression, NamedGroup};
48
    use crate::msgs::handshake::{
49
        CertificatePayloadTls13, CertificateRequestExtensions, CertificateRequestPayloadTls13,
50
        ClientHelloPayload, HelloRetryRequest, HelloRetryRequestExtensions, KeyShareEntry, Random,
51
        ServerExtensions, ServerExtensionsInput, ServerHelloPayload, ServerTicketRequestHint,
52
        SessionId,
53
    };
54
    use crate::server::common::ActiveCertifiedKey;
55
    use crate::sign;
56
    use crate::tls13::key_schedule::{
57
        KeyScheduleEarly, KeyScheduleHandshake, KeySchedulePreHandshake,
58
    };
59
    use crate::verify::DigitallySignedStruct;
60
61
    #[derive(PartialEq)]
62
    pub(super) enum EarlyDataDecision {
63
        Disabled,
64
        RequestedButRejected,
65
        Accepted,
66
    }
67
68
    pub(in crate::server) struct CompleteClientHelloHandling {
69
        pub(in crate::server) config: Arc<ServerConfig>,
70
        pub(in crate::server) transcript: HandshakeHash,
71
        pub(in crate::server) suite: &'static Tls13CipherSuite,
72
        pub(in crate::server) randoms: ConnectionRandoms,
73
        pub(in crate::server) done_retry: bool,
74
        pub(in crate::server) send_tickets: usize,
75
        pub(in crate::server) extra_exts: ServerExtensionsInput<'static>,
76
    }
77
78
0
    fn max_early_data_size(configured: u32) -> usize {
79
0
        if configured != 0 {
80
0
            configured as usize
81
        } else {
82
            // The relevant max_early_data_size may in fact be unknowable: if
83
            // we (the server) have turned off early_data but the client has
84
            // a stale ticket from when we allowed early_data: we'll naturally
85
            // reject early_data but need an upper bound on the amount of data
86
            // to drop.
87
            //
88
            // Use a single maximum-sized message.
89
0
            16384
90
        }
91
0
    }
92
93
    impl CompleteClientHelloHandling {
94
0
        fn check_binder(
95
0
            &self,
96
0
            suite: &'static Tls13CipherSuite,
97
0
            client_hello: &Message<'_>,
98
0
            psk: &[u8],
99
0
            binder: &[u8],
100
0
        ) -> bool {
101
0
            let binder_plaintext = match &client_hello.payload {
102
0
                MessagePayload::Handshake { parsed, encoded } => &encoded.bytes()[..encoded
103
0
                    .bytes()
104
0
                    .len()
105
0
                    .saturating_sub(parsed.total_binder_length())],
106
0
                _ => unreachable!(),
107
            };
108
109
0
            let handshake_hash = self
110
0
                .transcript
111
0
                .hash_given(binder_plaintext);
112
113
0
            let key_schedule = KeyScheduleEarly::new(suite, psk);
114
0
            let real_binder =
115
0
                key_schedule.resumption_psk_binder_key_and_sign_verify_data(&handshake_hash);
116
117
0
            ConstantTimeEq::ct_eq(real_binder.as_ref(), binder).into()
118
0
        }
119
120
0
        fn attempt_tls13_ticket_decryption(
121
0
            &mut self,
122
0
            ticket: &[u8],
123
0
        ) -> Option<persist::ServerSessionValue> {
124
0
            if self.config.ticketer.enabled() {
125
0
                self.config
126
0
                    .ticketer
127
0
                    .decrypt(ticket)
128
0
                    .and_then(|plain| persist::ServerSessionValue::read_bytes(&plain).ok())
129
            } else {
130
0
                self.config
131
0
                    .session_storage
132
0
                    .take(ticket)
133
0
                    .and_then(|plain| persist::ServerSessionValue::read_bytes(&plain).ok())
134
            }
135
0
        }
136
137
0
        pub(in crate::server) fn handle_client_hello(
138
0
            mut self,
139
0
            cx: &mut ServerContext<'_>,
140
0
            server_key: ActiveCertifiedKey<'_>,
141
0
            chm: &Message<'_>,
142
0
            client_hello: &ClientHelloPayload,
143
0
            selected_kxg: &'static dyn SupportedKxGroup,
144
0
            mut sigschemes_ext: Vec<SignatureScheme>,
145
0
        ) -> hs::NextStateOrError<'static> {
146
0
            if client_hello.compression_methods.len() != 1 {
147
0
                return Err(cx.common.send_fatal_alert(
148
0
                    AlertDescription::IllegalParameter,
149
0
                    PeerMisbehaved::OfferedIncorrectCompressions,
150
0
                ));
151
0
            }
152
153
0
            sigschemes_ext.retain(SignatureScheme::supported_in_tls13);
154
155
0
            let shares_ext = client_hello
156
0
                .key_shares
157
0
                .as_ref()
158
0
                .ok_or_else(|| {
159
0
                    cx.common.send_fatal_alert(
160
0
                        AlertDescription::HandshakeFailure,
161
0
                        PeerIncompatible::KeyShareExtensionRequired,
162
                    )
163
0
                })?;
164
165
0
            if client_hello.has_keyshare_extension_with_duplicates() {
166
0
                return Err(cx.common.send_fatal_alert(
167
0
                    AlertDescription::IllegalParameter,
168
0
                    PeerMisbehaved::OfferedDuplicateKeyShares,
169
0
                ));
170
0
            }
171
172
0
            if client_hello.has_certificate_compression_extension_with_duplicates() {
173
0
                return Err(cx.common.send_fatal_alert(
174
0
                    AlertDescription::IllegalParameter,
175
0
                    PeerMisbehaved::OfferedDuplicateCertificateCompressions,
176
0
                ));
177
0
            }
178
179
0
            let cert_compressor = client_hello
180
0
                .certificate_compression_algorithms
181
0
                .as_ref()
182
0
                .and_then(|offered|
183
                    // prefer server order when choosing a compression: the client's
184
                    // extension here does not denote any preference.
185
0
                    self.config
186
0
                        .cert_compressors
187
0
                        .iter()
188
0
                        .find(|compressor| offered.contains(&compressor.algorithm()))
189
0
                        .cloned());
190
191
0
            let early_data_requested = client_hello
192
0
                .early_data_request
193
0
                .is_some();
194
195
            // EarlyData extension is illegal in second ClientHello
196
0
            if self.done_retry && early_data_requested {
197
0
                return Err({
198
0
                    cx.common.send_fatal_alert(
199
0
                        AlertDescription::IllegalParameter,
200
0
                        PeerMisbehaved::EarlyDataAttemptedInSecondClientHello,
201
0
                    )
202
0
                });
203
0
            }
204
205
            // See if there is a KeyShare for the selected kx group.
206
0
            let chosen_share_and_kxg = shares_ext.iter().find_map(|share| {
207
0
                (share.group == selected_kxg.name()).then_some((share, selected_kxg))
208
0
            });
209
210
0
            let Some(chosen_share_and_kxg) = chosen_share_and_kxg else {
211
                // We don't have a suitable key share.  Send a HelloRetryRequest
212
                // for the mutually_preferred_group.
213
0
                self.transcript.add_message(chm);
214
215
0
                if self.done_retry {
216
0
                    return Err(cx.common.send_fatal_alert(
217
0
                        AlertDescription::IllegalParameter,
218
0
                        PeerMisbehaved::RefusedToFollowHelloRetryRequest,
219
0
                    ));
220
0
                }
221
222
0
                emit_hello_retry_request(
223
0
                    &mut self.transcript,
224
0
                    self.suite,
225
0
                    client_hello.session_id,
226
0
                    cx.common,
227
0
                    selected_kxg.name(),
228
                );
229
0
                emit_fake_ccs(cx.common);
230
231
0
                let skip_early_data = max_early_data_size(self.config.max_early_data_size);
232
233
0
                let next = Box::new(hs::ExpectClientHello {
234
0
                    config: self.config,
235
0
                    transcript: HandshakeHashOrBuffer::Hash(self.transcript),
236
0
                    #[cfg(feature = "tls12")]
237
0
                    session_id: SessionId::empty(),
238
0
                    #[cfg(feature = "tls12")]
239
0
                    using_ems: false,
240
0
                    done_retry: true,
241
0
                    send_tickets: self.send_tickets,
242
0
                    extra_exts: self.extra_exts,
243
0
                });
244
245
0
                return if early_data_requested {
246
0
                    Ok(Box::new(ExpectAndSkipRejectedEarlyData {
247
0
                        skip_data_left: skip_early_data,
248
0
                        next,
249
0
                    }))
250
                } else {
251
0
                    Ok(next)
252
                };
253
            };
254
255
0
            let mut chosen_psk_index = None;
256
0
            let mut resumedata = None;
257
258
0
            if let Some(psk_offer) = &client_hello.preshared_key_offer {
259
                // "A client MUST provide a "psk_key_exchange_modes" extension if it
260
                //  offers a "pre_shared_key" extension. If clients offer
261
                //  "pre_shared_key" without a "psk_key_exchange_modes" extension,
262
                //  servers MUST abort the handshake." - RFC8446 4.2.9
263
0
                if client_hello
264
0
                    .preshared_key_modes
265
0
                    .is_none()
266
                {
267
0
                    return Err(cx.common.send_fatal_alert(
268
0
                        AlertDescription::MissingExtension,
269
0
                        PeerMisbehaved::MissingPskModesExtension,
270
0
                    ));
271
0
                }
272
273
0
                if psk_offer.binders.is_empty() {
274
0
                    return Err(cx.common.send_fatal_alert(
275
0
                        AlertDescription::DecodeError,
276
0
                        PeerMisbehaved::MissingBinderInPskExtension,
277
0
                    ));
278
0
                }
279
280
0
                if psk_offer.binders.len() != psk_offer.identities.len() {
281
0
                    return Err(cx.common.send_fatal_alert(
282
0
                        AlertDescription::IllegalParameter,
283
0
                        PeerMisbehaved::PskExtensionWithMismatchedIdsAndBinders,
284
0
                    ));
285
0
                }
286
287
0
                let now = self.config.current_time()?;
288
289
0
                for (i, psk_id) in psk_offer.identities.iter().enumerate() {
290
0
                    let maybe_resume_data = self
291
0
                        .attempt_tls13_ticket_decryption(&psk_id.identity.0)
292
0
                        .map(|resumedata| {
293
0
                            resumedata.set_freshness(psk_id.obfuscated_ticket_age, now)
294
0
                        })
295
0
                        .filter(|resumedata| {
296
0
                            hs::can_resume(self.suite.into(), &cx.data.sni, false, resumedata)
297
0
                        });
298
299
0
                    let Some(resume) = maybe_resume_data else {
300
0
                        continue;
301
                    };
302
303
0
                    if !self.check_binder(
304
0
                        self.suite,
305
0
                        chm,
306
0
                        &resume.master_secret.0,
307
0
                        psk_offer.binders[i].as_ref(),
308
0
                    ) {
309
0
                        return Err(cx.common.send_fatal_alert(
310
0
                            AlertDescription::DecryptError,
311
0
                            PeerMisbehaved::IncorrectBinder,
312
0
                        ));
313
0
                    }
314
315
0
                    chosen_psk_index = Some(i);
316
0
                    resumedata = Some(resume);
317
0
                    break;
318
                }
319
0
            }
320
321
0
            if !client_hello
322
0
                .preshared_key_modes
323
0
                .as_ref()
324
0
                .map(|offer| offer.psk_dhe)
325
0
                .unwrap_or_default()
326
            {
327
0
                debug!("Client unwilling to resume, PSK_DHE_KE not offered");
328
0
                self.send_tickets = 0;
329
0
                chosen_psk_index = None;
330
0
                resumedata = None;
331
            } else {
332
                // RFC 9149: if the client sent a ticket_request extension and the
333
                // server has configured a max, honor the client's request.
334
0
                self.send_tickets = if self.config.max_tls13_tickets > 0 {
335
0
                    if let Some(req) = &client_hello.ticket_request {
336
0
                        let requested = usize::from(if resumedata.is_some() {
337
0
                            req.resumption_count
338
                        } else {
339
0
                            req.new_session_count
340
                        });
341
0
                        Ord::min(requested, self.config.max_tls13_tickets)
342
                    } else {
343
0
                        self.config.send_tls13_tickets
344
                    }
345
                } else {
346
0
                    self.config.send_tls13_tickets
347
                };
348
            }
349
350
0
            if let Some(resume) = &resumedata {
351
0
                cx.data.received_resumption_data = Some(resume.application_data.0.clone());
352
0
                cx.common
353
0
                    .peer_certificates
354
0
                    .clone_from(&resume.client_cert_chain);
355
0
            }
356
357
0
            let full_handshake = resumedata.is_none();
358
0
            self.transcript.add_message(chm);
359
0
            let key_schedule = emit_server_hello(
360
0
                &mut self.transcript,
361
0
                &self.randoms,
362
0
                self.suite,
363
0
                cx,
364
0
                &client_hello.session_id,
365
0
                chosen_share_and_kxg,
366
0
                chosen_psk_index,
367
0
                resumedata
368
0
                    .as_ref()
369
0
                    .map(|x| &x.master_secret.0[..]),
370
0
                &self.config,
371
0
            )?;
372
0
            if !self.done_retry {
373
0
                emit_fake_ccs(cx.common);
374
0
            }
375
376
0
            if full_handshake {
377
0
                cx.common
378
0
                    .handshake_kind
379
0
                    .get_or_insert(HandshakeKind::Full);
380
0
            } else {
381
0
                cx.common.handshake_kind = Some(HandshakeKind::Resumed);
382
0
            }
383
384
0
            let mut ocsp_response = server_key.get_ocsp();
385
0
            let mut flight = HandshakeFlightTls13::new(&mut self.transcript);
386
0
            let doing_early_data = emit_encrypted_extensions(
387
0
                &mut flight,
388
0
                self.suite,
389
0
                cx,
390
0
                &mut ocsp_response,
391
0
                client_hello,
392
0
                resumedata.as_ref(),
393
0
                self.extra_exts,
394
0
                &self.config,
395
0
                self.send_tickets,
396
0
            )?;
397
398
0
            let doing_client_auth = if full_handshake {
399
0
                let client_auth = emit_certificate_req_tls13(&mut flight, &self.config)?;
400
401
0
                if let Some(compressor) = cert_compressor {
402
0
                    emit_compressed_certificate_tls13(
403
0
                        &mut flight,
404
0
                        &self.config,
405
0
                        server_key.get_cert(),
406
0
                        ocsp_response,
407
0
                        compressor,
408
0
                    );
409
0
                } else {
410
0
                    emit_certificate_tls13(&mut flight, server_key.get_cert(), ocsp_response);
411
0
                }
412
0
                emit_certificate_verify_tls13(
413
0
                    &mut flight,
414
0
                    cx.common,
415
0
                    server_key.get_key(),
416
0
                    &sigschemes_ext,
417
0
                )?;
418
0
                client_auth
419
            } else {
420
0
                false
421
            };
422
423
            // If we're not doing early data, then the next messages we receive
424
            // are encrypted with the handshake keys.
425
0
            match doing_early_data {
426
0
                EarlyDataDecision::Disabled => {
427
0
                    key_schedule.set_handshake_decrypter(None, cx.common);
428
0
                    cx.data.early_data.reject();
429
0
                }
430
                EarlyDataDecision::RequestedButRejected => {
431
0
                    debug!(
432
0
                        "Client requested early_data, but not accepted: switching to handshake keys with trial decryption"
433
                    );
434
0
                    key_schedule.set_handshake_decrypter(
435
0
                        Some(max_early_data_size(self.config.max_early_data_size)),
436
0
                        cx.common,
437
                    );
438
0
                    cx.data.early_data.reject();
439
                }
440
0
                EarlyDataDecision::Accepted => {
441
0
                    cx.data
442
0
                        .early_data
443
0
                        .accept(self.config.max_early_data_size as usize);
444
0
                }
445
            }
446
447
0
            cx.common.check_aligned_handshake()?;
448
0
            let key_schedule_traffic =
449
0
                emit_finished_tls13(flight, &self.randoms, cx, key_schedule, &self.config);
450
451
0
            if !doing_client_auth && self.config.send_half_rtt_data {
452
0
                // Application data can be sent immediately after Finished, in one
453
0
                // flight.  However, if client auth is enabled, we don't want to send
454
0
                // application data to an unauthenticated peer.
455
0
                cx.common
456
0
                    .start_outgoing_traffic(&mut cx.sendable_plaintext);
457
0
            }
458
459
0
            if doing_client_auth {
460
0
                if self
461
0
                    .config
462
0
                    .cert_decompressors
463
0
                    .is_empty()
464
                {
465
0
                    Ok(Box::new(ExpectCertificate {
466
0
                        config: self.config,
467
0
                        transcript: self.transcript,
468
0
                        suite: self.suite,
469
0
                        key_schedule: key_schedule_traffic,
470
0
                        send_tickets: self.send_tickets,
471
0
                        message_already_in_transcript: false,
472
0
                    }))
473
                } else {
474
0
                    Ok(Box::new(ExpectCertificateOrCompressedCertificate {
475
0
                        config: self.config,
476
0
                        transcript: self.transcript,
477
0
                        suite: self.suite,
478
0
                        key_schedule: key_schedule_traffic,
479
0
                        send_tickets: self.send_tickets,
480
0
                    }))
481
                }
482
0
            } else if doing_early_data == EarlyDataDecision::Accepted && !cx.common.is_quic() {
483
                // Not used for QUIC: RFC 9001 §8.3: Clients MUST NOT send the EndOfEarlyData
484
                // message. A server MUST treat receipt of a CRYPTO frame in a 0-RTT packet as a
485
                // connection error of type PROTOCOL_VIOLATION.
486
0
                Ok(Box::new(ExpectEarlyData {
487
0
                    config: self.config,
488
0
                    transcript: self.transcript,
489
0
                    suite: self.suite,
490
0
                    key_schedule: key_schedule_traffic,
491
0
                    send_tickets: self.send_tickets,
492
0
                }))
493
            } else {
494
0
                Ok(Box::new(ExpectFinished {
495
0
                    config: self.config,
496
0
                    transcript: self.transcript,
497
0
                    suite: self.suite,
498
0
                    key_schedule: key_schedule_traffic,
499
0
                    send_tickets: self.send_tickets,
500
0
                }))
501
            }
502
0
        }
503
    }
504
505
0
    fn emit_server_hello(
506
0
        transcript: &mut HandshakeHash,
507
0
        randoms: &ConnectionRandoms,
508
0
        suite: &'static Tls13CipherSuite,
509
0
        cx: &mut ServerContext<'_>,
510
0
        session_id: &SessionId,
511
0
        share_and_kxgroup: (&KeyShareEntry, &'static dyn SupportedKxGroup),
512
0
        chosen_psk_idx: Option<usize>,
513
0
        resuming_psk: Option<&[u8]>,
514
0
        config: &ServerConfig,
515
0
    ) -> Result<KeyScheduleHandshake, Error> {
516
        // Prepare key exchange; the caller already found the matching SupportedKxGroup
517
0
        let (share, kxgroup) = share_and_kxgroup;
518
0
        debug_assert_eq!(kxgroup.name(), share.group);
519
0
        let ckx = kxgroup
520
0
            .start_and_complete(&share.payload.0)
521
0
            .map_err(|err| {
522
0
                cx.common
523
0
                    .send_fatal_alert(AlertDescription::IllegalParameter, err)
524
0
            })?;
525
0
        cx.common.kx_state.complete();
526
527
0
        let extensions = Box::new(ServerExtensions {
528
0
            key_share: Some(KeyShareEntry::new(ckx.group, ckx.pub_key)),
529
0
            selected_version: Some(ProtocolVersion::TLSv1_3),
530
0
            preshared_key: chosen_psk_idx.map(|idx| idx as u16),
531
0
            ..Default::default()
532
        });
533
534
0
        let sh = Message {
535
0
            version: ProtocolVersion::TLSv1_2,
536
0
            payload: MessagePayload::handshake(HandshakeMessagePayload(
537
0
                HandshakePayload::ServerHello(ServerHelloPayload {
538
0
                    legacy_version: ProtocolVersion::TLSv1_2,
539
0
                    random: Random::from(randoms.server),
540
0
                    session_id: *session_id,
541
0
                    cipher_suite: suite.common.suite,
542
0
                    compression_method: Compression::Null,
543
0
                    extensions,
544
0
                }),
545
0
            )),
546
0
        };
547
548
0
        cx.common.check_aligned_handshake()?;
549
550
0
        let client_hello_hash = transcript.hash_given(&[]);
551
552
0
        trace!("sending server hello {sh:?}");
553
0
        transcript.add_message(&sh);
554
0
        cx.common.send_msg(sh, false);
555
556
        // Start key schedule
557
0
        let key_schedule_pre_handshake = if let Some(psk) = resuming_psk {
558
0
            let early_key_schedule = KeyScheduleEarly::new(suite, psk);
559
0
            early_key_schedule.client_early_traffic_secret(
560
0
                &client_hello_hash,
561
0
                &*config.key_log,
562
0
                &randoms.client,
563
0
                cx.common,
564
            );
565
566
0
            KeySchedulePreHandshake::from(early_key_schedule)
567
        } else {
568
0
            KeySchedulePreHandshake::new(suite)
569
        };
570
571
        // Do key exchange
572
0
        let key_schedule = key_schedule_pre_handshake.into_handshake(ckx.secret);
573
574
0
        let handshake_hash = transcript.current_hash();
575
0
        let key_schedule = key_schedule.derive_server_handshake_secrets(
576
0
            handshake_hash,
577
0
            &*config.key_log,
578
0
            &randoms.client,
579
0
            cx.common,
580
        );
581
582
0
        Ok(key_schedule)
583
0
    }
584
585
0
    fn emit_fake_ccs(common: &mut CommonState) {
586
0
        if common.is_quic() {
587
0
            return;
588
0
        }
589
0
        let m = Message {
590
0
            version: ProtocolVersion::TLSv1_2,
591
0
            payload: MessagePayload::ChangeCipherSpec(ChangeCipherSpecPayload {}),
592
0
        };
593
0
        common.send_msg(m, false);
594
0
    }
595
596
0
    fn emit_hello_retry_request(
597
0
        transcript: &mut HandshakeHash,
598
0
        suite: &'static Tls13CipherSuite,
599
0
        session_id: SessionId,
600
0
        common: &mut CommonState,
601
0
        group: NamedGroup,
602
0
    ) {
603
0
        let req = HelloRetryRequest {
604
0
            legacy_version: ProtocolVersion::TLSv1_2,
605
0
            session_id,
606
0
            cipher_suite: suite.common.suite,
607
0
            extensions: HelloRetryRequestExtensions {
608
0
                key_share: Some(group),
609
0
                supported_versions: Some(ProtocolVersion::TLSv1_3),
610
0
                ..Default::default()
611
0
            },
612
0
        };
613
614
0
        let m = Message {
615
0
            version: ProtocolVersion::TLSv1_2,
616
0
            payload: MessagePayload::handshake(HandshakeMessagePayload(
617
0
                HandshakePayload::HelloRetryRequest(req),
618
0
            )),
619
0
        };
620
621
0
        trace!("Requesting retry {m:?}");
622
0
        transcript.rollup_for_hrr();
623
0
        transcript.add_message(&m);
624
0
        common.send_msg(m, false);
625
0
        common.handshake_kind = Some(HandshakeKind::FullWithHelloRetryRequest);
626
0
    }
627
628
0
    fn decide_if_early_data_allowed(
629
0
        cx: &mut ServerContext<'_>,
630
0
        client_hello: &ClientHelloPayload,
631
0
        resumedata: Option<&persist::ServerSessionValue>,
632
0
        suite: &'static Tls13CipherSuite,
633
0
        config: &ServerConfig,
634
0
    ) -> EarlyDataDecision {
635
0
        let early_data_requested = client_hello
636
0
            .early_data_request
637
0
            .is_some();
638
0
        let rejected_or_disabled = match early_data_requested {
639
0
            true => EarlyDataDecision::RequestedButRejected,
640
0
            false => EarlyDataDecision::Disabled,
641
        };
642
643
0
        let Some(resume) = resumedata else {
644
            // never any early data if not resuming.
645
0
            return rejected_or_disabled;
646
        };
647
648
        /* Non-zero max_early_data_size controls whether early_data is allowed at all.
649
         * We also require stateful resumption. */
650
0
        let early_data_configured = config.max_early_data_size > 0 && !config.ticketer.enabled();
651
652
        /* "For PSKs provisioned via NewSessionTicket, a server MUST validate
653
         *  that the ticket age for the selected PSK identity (computed by
654
         *  subtracting ticket_age_add from PskIdentity.obfuscated_ticket_age
655
         *  modulo 2^32) is within a small tolerance of the time since the ticket
656
         *  was issued (see Section 8)." -- this is implemented in ServerSessionValue::set_freshness()
657
         *  and related.
658
         *
659
         * "In order to accept early data, the server [...] MUST verify that the
660
         *  following values are the same as those associated with the
661
         *  selected PSK:
662
         *
663
         *  - The TLS version number
664
         *  - The selected cipher suite
665
         *  - The selected ALPN [RFC7301] protocol, if any"
666
         *
667
         * (RFC8446, 4.2.10) */
668
0
        let early_data_possible = early_data_requested
669
0
            && resume.is_fresh()
670
0
            && Some(resume.version) == cx.common.negotiated_version
671
0
            && resume.cipher_suite == suite.common.suite
672
0
            && resume.alpn.as_ref().map(|p| &p.0[..]) == cx.common.alpn_protocol.as_deref();
673
674
0
        if early_data_configured && early_data_possible && !cx.data.early_data.was_rejected() {
675
0
            EarlyDataDecision::Accepted
676
        } else {
677
0
            if cx.common.is_quic() {
678
0
                // Clobber value set in tls13::emit_server_hello
679
0
                cx.common.quic.early_secret = None;
680
0
            }
681
682
0
            rejected_or_disabled
683
        }
684
0
    }
685
686
0
    fn emit_encrypted_extensions(
687
0
        flight: &mut HandshakeFlightTls13<'_>,
688
0
        suite: &'static Tls13CipherSuite,
689
0
        cx: &mut ServerContext<'_>,
690
0
        ocsp_response: &mut Option<&[u8]>,
691
0
        hello: &ClientHelloPayload,
692
0
        resumedata: Option<&persist::ServerSessionValue>,
693
0
        extra_exts: ServerExtensionsInput<'static>,
694
0
        config: &ServerConfig,
695
0
        send_tickets: usize,
696
0
    ) -> Result<EarlyDataDecision, Error> {
697
0
        let mut ep = hs::ExtensionProcessing::new(extra_exts);
698
0
        ep.process_common(config, cx, ocsp_response, hello, resumedata)?;
699
700
        // RFC 9149: echo the expected ticket count if the client sent the extension.
701
0
        if hello.ticket_request.is_some() && config.max_tls13_tickets > 0 {
702
0
            ep.extensions.ticket_request = Some(ServerTicketRequestHint {
703
0
                expected_count: Ord::min(send_tickets, usize::from(u8::MAX)) as u8,
704
0
            });
705
0
        }
706
707
0
        let early_data = decide_if_early_data_allowed(cx, hello, resumedata, suite, config);
708
0
        if early_data == EarlyDataDecision::Accepted {
709
0
            ep.extensions.early_data_ack = Some(());
710
0
        }
711
712
0
        let ee = HandshakeMessagePayload(HandshakePayload::EncryptedExtensions(ep.extensions));
713
714
0
        trace!("sending encrypted extensions {ee:?}");
715
0
        flight.add(ee);
716
0
        Ok(early_data)
717
0
    }
718
719
0
    fn emit_certificate_req_tls13(
720
0
        flight: &mut HandshakeFlightTls13<'_>,
721
0
        config: &ServerConfig,
722
0
    ) -> Result<bool, Error> {
723
0
        if !config.verifier.offer_client_auth() {
724
0
            return Ok(false);
725
0
        }
726
727
0
        let cr = CertificateRequestPayloadTls13 {
728
0
            context: PayloadU8::empty(),
729
            extensions: CertificateRequestExtensions {
730
0
                signature_algorithms: Some(
731
0
                    config
732
0
                        .verifier
733
0
                        .supported_verify_schemes(),
734
0
                ),
735
0
                certificate_compression_algorithms: match config.cert_decompressors.as_slice() {
736
0
                    &[] => None,
737
0
                    decomps => Some(
738
0
                        decomps
739
0
                            .iter()
740
0
                            .map(|decomp| decomp.algorithm())
741
0
                            .collect(),
742
                    ),
743
                },
744
0
                authority_names: match config.verifier.root_hint_subjects() {
745
0
                    &[] => None,
746
0
                    authorities => Some(authorities.to_vec()),
747
                },
748
            },
749
        };
750
751
0
        let creq = HandshakeMessagePayload(HandshakePayload::CertificateRequestTls13(cr));
752
753
0
        trace!("Sending CertificateRequest {creq:?}");
754
0
        flight.add(creq);
755
0
        Ok(true)
756
0
    }
757
758
0
    fn emit_certificate_tls13(
759
0
        flight: &mut HandshakeFlightTls13<'_>,
760
0
        cert_chain: &[CertificateDer<'static>],
761
0
        ocsp_response: Option<&[u8]>,
762
0
    ) {
763
0
        let cert = HandshakeMessagePayload(HandshakePayload::CertificateTls13(
764
0
            CertificatePayloadTls13::new(cert_chain.iter(), ocsp_response),
765
0
        ));
766
767
0
        trace!("sending certificate {cert:?}");
768
0
        flight.add(cert);
769
0
    }
770
771
0
    fn emit_compressed_certificate_tls13(
772
0
        flight: &mut HandshakeFlightTls13<'_>,
773
0
        config: &ServerConfig,
774
0
        cert_chain: &[CertificateDer<'static>],
775
0
        ocsp_response: Option<&[u8]>,
776
0
        cert_compressor: &'static dyn CertCompressor,
777
0
    ) {
778
0
        let payload = CertificatePayloadTls13::new(cert_chain.iter(), ocsp_response);
779
780
0
        let Ok(entry) = config
781
0
            .cert_compression_cache
782
0
            .compression_for(cert_compressor, &payload)
783
        else {
784
0
            return emit_certificate_tls13(flight, cert_chain, ocsp_response);
785
        };
786
787
0
        let c = HandshakeMessagePayload(HandshakePayload::CompressedCertificate(
788
0
            entry.compressed_cert_payload(),
789
0
        ));
790
791
0
        trace!("sending compressed certificate {c:?}");
792
0
        flight.add(c);
793
0
    }
794
795
0
    fn emit_certificate_verify_tls13(
796
0
        flight: &mut HandshakeFlightTls13<'_>,
797
0
        common: &mut CommonState,
798
0
        signing_key: &dyn sign::SigningKey,
799
0
        schemes: &[SignatureScheme],
800
0
    ) -> Result<(), Error> {
801
0
        let message = construct_server_verify_message(&flight.transcript.current_hash());
802
803
0
        let signer = signing_key
804
0
            .choose_scheme(schemes)
805
0
            .ok_or_else(|| {
806
0
                common.send_fatal_alert(
807
0
                    AlertDescription::HandshakeFailure,
808
0
                    PeerIncompatible::NoSignatureSchemesInCommon,
809
                )
810
0
            })?;
811
812
0
        let scheme = signer.scheme();
813
0
        let sig = signer.sign(message.as_ref())?;
814
815
0
        let cv = DigitallySignedStruct::new(scheme, sig);
816
817
0
        let cv = HandshakeMessagePayload(HandshakePayload::CertificateVerify(cv));
818
819
0
        trace!("sending certificate-verify {cv:?}");
820
0
        flight.add(cv);
821
0
        Ok(())
822
0
    }
823
824
0
    fn emit_finished_tls13(
825
0
        mut flight: HandshakeFlightTls13<'_>,
826
0
        randoms: &ConnectionRandoms,
827
0
        cx: &mut ServerContext<'_>,
828
0
        key_schedule: KeyScheduleHandshake,
829
0
        config: &ServerConfig,
830
0
    ) -> KeyScheduleTrafficWithClientFinishedPending {
831
0
        let handshake_hash = flight.transcript.current_hash();
832
0
        let verify_data = key_schedule.sign_server_finish(&handshake_hash);
833
0
        let verify_data_payload = Payload::new(verify_data.as_ref());
834
835
0
        let fin = HandshakeMessagePayload(HandshakePayload::Finished(verify_data_payload));
836
837
0
        trace!("sending finished {fin:?}");
838
0
        flight.add(fin);
839
0
        let hash_at_server_fin = flight.transcript.current_hash();
840
0
        flight.finish(cx.common);
841
842
        // Now move to application data keys.  Read key change is deferred until
843
        // the Finish message is received & validated.
844
0
        key_schedule.into_traffic_with_client_finished_pending(
845
0
            hash_at_server_fin,
846
0
            &*config.key_log,
847
0
            &randoms.client,
848
0
            cx.common,
849
        )
850
0
    }
851
}
852
853
struct ExpectAndSkipRejectedEarlyData {
854
    skip_data_left: usize,
855
    next: Box<hs::ExpectClientHello>,
856
}
857
858
impl State<ServerConnectionData> for ExpectAndSkipRejectedEarlyData {
859
0
    fn handle<'m>(
860
0
        mut self: Box<Self>,
861
0
        cx: &mut ServerContext<'_>,
862
0
        m: Message<'m>,
863
0
    ) -> hs::NextStateOrError<'m>
864
0
    where
865
0
        Self: 'm,
866
    {
867
        /* "The server then ignores early data by skipping all records with an external
868
         *  content type of "application_data" (indicating that they are encrypted),
869
         *  up to the configured max_early_data_size."
870
         * (RFC8446, 14.2.10) */
871
0
        if let MessagePayload::ApplicationData(skip_data) = &m.payload {
872
0
            if skip_data.bytes().len() <= self.skip_data_left {
873
0
                self.skip_data_left -= skip_data.bytes().len();
874
0
                return Ok(self);
875
0
            }
876
0
        }
877
878
0
        self.next.handle(cx, m)
879
0
    }
880
881
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
882
0
        self
883
0
    }
884
}
885
886
struct ExpectCertificateOrCompressedCertificate {
887
    config: Arc<ServerConfig>,
888
    transcript: HandshakeHash,
889
    suite: &'static Tls13CipherSuite,
890
    key_schedule: KeyScheduleTrafficWithClientFinishedPending,
891
    send_tickets: usize,
892
}
893
894
impl State<ServerConnectionData> for ExpectCertificateOrCompressedCertificate {
895
0
    fn handle<'m>(
896
0
        self: Box<Self>,
897
0
        cx: &mut ServerContext<'_>,
898
0
        m: Message<'m>,
899
0
    ) -> hs::NextStateOrError<'m>
900
0
    where
901
0
        Self: 'm,
902
    {
903
0
        match m.payload {
904
            MessagePayload::Handshake {
905
                parsed: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
906
                ..
907
0
            } => Box::new(ExpectCertificate {
908
0
                config: self.config,
909
0
                transcript: self.transcript,
910
0
                suite: self.suite,
911
0
                key_schedule: self.key_schedule,
912
0
                send_tickets: self.send_tickets,
913
0
                message_already_in_transcript: false,
914
0
            })
915
0
            .handle(cx, m),
916
917
            MessagePayload::Handshake {
918
                parsed: HandshakeMessagePayload(HandshakePayload::CompressedCertificate(..)),
919
                ..
920
0
            } => Box::new(ExpectCompressedCertificate {
921
0
                config: self.config,
922
0
                transcript: self.transcript,
923
0
                suite: self.suite,
924
0
                key_schedule: self.key_schedule,
925
0
                send_tickets: self.send_tickets,
926
0
            })
927
0
            .handle(cx, m),
928
929
0
            payload => Err(inappropriate_handshake_message(
930
0
                &payload,
931
0
                &[ContentType::Handshake],
932
0
                &[
933
0
                    HandshakeType::Certificate,
934
0
                    HandshakeType::CompressedCertificate,
935
0
                ],
936
0
            )),
937
        }
938
0
    }
939
940
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
941
0
        self
942
0
    }
943
}
944
945
struct ExpectCompressedCertificate {
946
    config: Arc<ServerConfig>,
947
    transcript: HandshakeHash,
948
    suite: &'static Tls13CipherSuite,
949
    key_schedule: KeyScheduleTrafficWithClientFinishedPending,
950
    send_tickets: usize,
951
}
952
953
impl State<ServerConnectionData> for ExpectCompressedCertificate {
954
0
    fn handle<'m>(
955
0
        mut self: Box<Self>,
956
0
        cx: &mut ServerContext<'_>,
957
0
        m: Message<'m>,
958
0
    ) -> hs::NextStateOrError<'m>
959
0
    where
960
0
        Self: 'm,
961
    {
962
0
        self.transcript.add_message(&m);
963
0
        let compressed_cert = require_handshake_msg_move!(
964
            m,
965
            HandshakeType::CompressedCertificate,
966
            HandshakePayload::CompressedCertificate
967
0
        )?;
968
969
0
        let selected_decompressor = self
970
0
            .config
971
0
            .cert_decompressors
972
0
            .iter()
973
0
            .find(|item| item.algorithm() == compressed_cert.alg);
974
975
0
        let Some(decompressor) = selected_decompressor else {
976
0
            return Err(cx.common.send_fatal_alert(
977
0
                AlertDescription::BadCertificate,
978
0
                PeerMisbehaved::SelectedUnofferedCertCompression,
979
0
            ));
980
        };
981
982
0
        if compressed_cert.uncompressed_len as usize > CERTIFICATE_MAX_SIZE_LIMIT {
983
0
            return Err(cx.common.send_fatal_alert(
984
0
                AlertDescription::BadCertificate,
985
0
                InvalidMessage::MessageTooLarge,
986
0
            ));
987
0
        }
988
989
0
        let mut decompress_buffer = vec![0u8; compressed_cert.uncompressed_len as usize];
990
        if let Err(compress::DecompressionFailed) =
991
0
            decompressor.decompress(compressed_cert.compressed.0.bytes(), &mut decompress_buffer)
992
        {
993
0
            return Err(cx.common.send_fatal_alert(
994
0
                AlertDescription::BadCertificate,
995
0
                PeerMisbehaved::InvalidCertCompression,
996
0
            ));
997
0
        }
998
999
0
        let cert_payload =
1000
0
            match CertificatePayloadTls13::read(&mut Reader::init(&decompress_buffer)) {
1001
0
                Ok(cm) => cm,
1002
0
                Err(err) => {
1003
0
                    return Err(cx
1004
0
                        .common
1005
0
                        .send_fatal_alert(AlertDescription::BadCertificate, err));
1006
                }
1007
            };
1008
0
        trace!(
1009
0
            "Client certificate decompressed using {:?} ({} bytes -> {})",
1010
            compressed_cert.alg,
1011
0
            compressed_cert
1012
0
                .compressed
1013
0
                .0
1014
0
                .bytes()
1015
0
                .len(),
1016
            compressed_cert.uncompressed_len,
1017
        );
1018
1019
0
        let m = Message {
1020
0
            version: ProtocolVersion::TLSv1_3,
1021
0
            payload: MessagePayload::handshake(HandshakeMessagePayload(
1022
0
                HandshakePayload::CertificateTls13(cert_payload.into_owned()),
1023
0
            )),
1024
0
        };
1025
1026
0
        Box::new(ExpectCertificate {
1027
0
            config: self.config,
1028
0
            transcript: self.transcript,
1029
0
            suite: self.suite,
1030
0
            key_schedule: self.key_schedule,
1031
0
            send_tickets: self.send_tickets,
1032
0
            message_already_in_transcript: true,
1033
0
        })
1034
0
        .handle(cx, m)
1035
0
    }
1036
1037
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1038
0
        self
1039
0
    }
1040
}
1041
1042
struct ExpectCertificate {
1043
    config: Arc<ServerConfig>,
1044
    transcript: HandshakeHash,
1045
    suite: &'static Tls13CipherSuite,
1046
    key_schedule: KeyScheduleTrafficWithClientFinishedPending,
1047
    send_tickets: usize,
1048
    message_already_in_transcript: bool,
1049
}
1050
1051
impl State<ServerConnectionData> for ExpectCertificate {
1052
0
    fn handle<'m>(
1053
0
        mut self: Box<Self>,
1054
0
        cx: &mut ServerContext<'_>,
1055
0
        m: Message<'m>,
1056
0
    ) -> hs::NextStateOrError<'m>
1057
0
    where
1058
0
        Self: 'm,
1059
    {
1060
0
        if !self.message_already_in_transcript {
1061
0
            self.transcript.add_message(&m);
1062
0
        }
1063
0
        let certp = require_handshake_msg_move!(
1064
            m,
1065
            HandshakeType::Certificate,
1066
            HandshakePayload::CertificateTls13
1067
0
        )?;
1068
1069
        // We don't send any CertificateRequest extensions, so any extensions
1070
        // here are illegal.
1071
0
        if certp
1072
0
            .entries
1073
0
            .iter()
1074
0
            .any(|e| !e.extensions.only_contains(&[]))
1075
        {
1076
0
            return Err(PeerMisbehaved::UnsolicitedCertExtension.into());
1077
0
        }
1078
1079
0
        let client_cert = certp.into_certificate_chain();
1080
1081
0
        let mandatory = self
1082
0
            .config
1083
0
            .verifier
1084
0
            .client_auth_mandatory();
1085
1086
0
        let Some((end_entity, intermediates)) = client_cert.split_first() else {
1087
0
            if !mandatory {
1088
0
                debug!("client auth requested but no certificate supplied");
1089
0
                self.transcript.abandon_client_auth();
1090
0
                return Ok(Box::new(ExpectFinished {
1091
0
                    config: self.config,
1092
0
                    suite: self.suite,
1093
0
                    key_schedule: self.key_schedule,
1094
0
                    transcript: self.transcript,
1095
0
                    send_tickets: self.send_tickets,
1096
0
                }));
1097
0
            }
1098
1099
0
            return Err(cx.common.send_fatal_alert(
1100
0
                AlertDescription::CertificateRequired,
1101
0
                Error::NoCertificatesPresented,
1102
0
            ));
1103
        };
1104
1105
0
        let now = self.config.current_time()?;
1106
1107
0
        self.config
1108
0
            .verifier
1109
0
            .verify_client_cert(end_entity, intermediates, now)
1110
0
            .map_err(|err| {
1111
0
                cx.common
1112
0
                    .send_cert_verify_error_alert(err)
1113
0
            })?;
1114
1115
0
        Ok(Box::new(ExpectCertificateVerify {
1116
0
            config: self.config,
1117
0
            suite: self.suite,
1118
0
            transcript: self.transcript,
1119
0
            key_schedule: self.key_schedule,
1120
0
            client_cert: client_cert.into_owned(),
1121
0
            send_tickets: self.send_tickets,
1122
0
        }))
1123
0
    }
1124
1125
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1126
0
        self
1127
0
    }
1128
}
1129
1130
struct ExpectCertificateVerify {
1131
    config: Arc<ServerConfig>,
1132
    transcript: HandshakeHash,
1133
    suite: &'static Tls13CipherSuite,
1134
    key_schedule: KeyScheduleTrafficWithClientFinishedPending,
1135
    client_cert: CertificateChain<'static>,
1136
    send_tickets: usize,
1137
}
1138
1139
impl State<ServerConnectionData> for ExpectCertificateVerify {
1140
0
    fn handle<'m>(
1141
0
        mut self: Box<Self>,
1142
0
        cx: &mut ServerContext<'_>,
1143
0
        m: Message<'m>,
1144
0
    ) -> hs::NextStateOrError<'m>
1145
0
    where
1146
0
        Self: 'm,
1147
    {
1148
0
        let rc = {
1149
0
            let sig = require_handshake_msg!(
1150
                m,
1151
                HandshakeType::CertificateVerify,
1152
                HandshakePayload::CertificateVerify
1153
0
            )?;
1154
0
            let handshake_hash = self.transcript.current_hash();
1155
0
            self.transcript.abandon_client_auth();
1156
0
            let certs = &self.client_cert;
1157
0
            let msg = construct_client_verify_message(&handshake_hash);
1158
1159
0
            self.config
1160
0
                .verifier
1161
0
                .verify_tls13_signature(msg.as_ref(), &certs[0], sig)
1162
        };
1163
1164
0
        if let Err(e) = rc {
1165
0
            return Err(cx
1166
0
                .common
1167
0
                .send_cert_verify_error_alert(e));
1168
0
        }
1169
1170
0
        trace!("client CertificateVerify OK");
1171
0
        cx.common.peer_certificates = Some(self.client_cert);
1172
1173
0
        self.transcript.add_message(&m);
1174
0
        Ok(Box::new(ExpectFinished {
1175
0
            config: self.config,
1176
0
            suite: self.suite,
1177
0
            key_schedule: self.key_schedule,
1178
0
            transcript: self.transcript,
1179
0
            send_tickets: self.send_tickets,
1180
0
        }))
1181
0
    }
1182
1183
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1184
0
        self
1185
0
    }
1186
}
1187
1188
// --- Process (any number of) early ApplicationData messages,
1189
//     followed by a terminating handshake EndOfEarlyData message ---
1190
1191
struct ExpectEarlyData {
1192
    config: Arc<ServerConfig>,
1193
    transcript: HandshakeHash,
1194
    suite: &'static Tls13CipherSuite,
1195
    key_schedule: KeyScheduleTrafficWithClientFinishedPending,
1196
    send_tickets: usize,
1197
}
1198
1199
impl State<ServerConnectionData> for ExpectEarlyData {
1200
0
    fn handle<'m>(
1201
0
        mut self: Box<Self>,
1202
0
        cx: &mut ServerContext<'_>,
1203
0
        m: Message<'m>,
1204
0
    ) -> hs::NextStateOrError<'m>
1205
0
    where
1206
0
        Self: 'm,
1207
    {
1208
0
        match m.payload {
1209
0
            MessagePayload::ApplicationData(payload) => {
1210
0
                match cx
1211
0
                    .data
1212
0
                    .early_data
1213
0
                    .take_received_plaintext(payload)
1214
                {
1215
0
                    true => Ok(self),
1216
0
                    false => Err(cx.common.send_fatal_alert(
1217
0
                        AlertDescription::UnexpectedMessage,
1218
0
                        PeerMisbehaved::TooMuchEarlyDataReceived,
1219
0
                    )),
1220
                }
1221
            }
1222
            MessagePayload::Handshake {
1223
                parsed: HandshakeMessagePayload(HandshakePayload::EndOfEarlyData),
1224
                ..
1225
            } => {
1226
0
                self.key_schedule
1227
0
                    .update_decrypter(cx.common);
1228
0
                self.transcript.add_message(&m);
1229
0
                Ok(Box::new(ExpectFinished {
1230
0
                    config: self.config,
1231
0
                    suite: self.suite,
1232
0
                    key_schedule: self.key_schedule,
1233
0
                    transcript: self.transcript,
1234
0
                    send_tickets: self.send_tickets,
1235
0
                }))
1236
            }
1237
0
            payload => Err(inappropriate_handshake_message(
1238
0
                &payload,
1239
0
                &[ContentType::ApplicationData, ContentType::Handshake],
1240
0
                &[HandshakeType::EndOfEarlyData],
1241
0
            )),
1242
        }
1243
0
    }
1244
1245
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1246
0
        self
1247
0
    }
1248
}
1249
1250
// --- Process client's Finished ---
1251
0
fn get_server_session_value(
1252
0
    suite: &'static Tls13CipherSuite,
1253
0
    resumption: &KeyScheduleResumption,
1254
0
    cx: &ServerContext<'_>,
1255
0
    nonce: &[u8],
1256
0
    time_now: UnixTime,
1257
0
    age_obfuscation_offset: u32,
1258
0
) -> persist::ServerSessionValue {
1259
0
    let version = ProtocolVersion::TLSv1_3;
1260
1261
0
    let secret = resumption.derive_ticket_psk(nonce);
1262
1263
0
    persist::ServerSessionValue::new(
1264
0
        cx.data.sni.as_ref(),
1265
0
        version,
1266
0
        suite.common.suite,
1267
0
        secret.as_ref(),
1268
0
        cx.common.peer_certificates.clone(),
1269
0
        cx.common.alpn_protocol.clone(),
1270
0
        cx.data.resumption_data.clone(),
1271
0
        time_now,
1272
0
        age_obfuscation_offset,
1273
    )
1274
0
}
1275
1276
struct ExpectFinished {
1277
    config: Arc<ServerConfig>,
1278
    transcript: HandshakeHash,
1279
    suite: &'static Tls13CipherSuite,
1280
    key_schedule: KeyScheduleTrafficWithClientFinishedPending,
1281
    send_tickets: usize,
1282
}
1283
1284
impl ExpectFinished {
1285
0
    fn emit_ticket(
1286
0
        flight: &mut HandshakeFlightTls13<'_>,
1287
0
        suite: &'static Tls13CipherSuite,
1288
0
        cx: &ServerContext<'_>,
1289
0
        resumption: &KeyScheduleResumption,
1290
0
        config: &ServerConfig,
1291
0
    ) -> Result<(), Error> {
1292
0
        let secure_random = config.provider.secure_random;
1293
0
        let nonce = rand::random_vec(secure_random, 32)?;
1294
0
        let age_add = rand::random_u32(secure_random)?;
1295
1296
0
        let now = config.current_time()?;
1297
1298
0
        let plain =
1299
0
            get_server_session_value(suite, resumption, cx, &nonce, now, age_add).get_encoding();
1300
1301
0
        let stateless = config.ticketer.enabled();
1302
0
        let (ticket, lifetime) = if stateless {
1303
0
            let Some(ticket) = config.ticketer.encrypt(&plain) else {
1304
0
                return Ok(());
1305
            };
1306
0
            (ticket, config.ticketer.lifetime())
1307
        } else {
1308
0
            let id = rand::random_vec(secure_random, 32)?;
1309
0
            let stored = config
1310
0
                .session_storage
1311
0
                .put(id.clone(), plain);
1312
0
            if !stored {
1313
0
                trace!("resumption not available; not issuing ticket");
1314
0
                return Ok(());
1315
0
            }
1316
0
            let stateful_lifetime = 24 * 60 * 60; // this is a bit of a punt
1317
0
            (id, stateful_lifetime)
1318
        };
1319
1320
0
        let mut payload = NewSessionTicketPayloadTls13::new(lifetime, age_add, nonce, ticket);
1321
1322
0
        if config.max_early_data_size > 0 {
1323
0
            if !stateless {
1324
0
                payload.extensions.max_early_data_size = Some(config.max_early_data_size);
1325
0
            } else {
1326
                // We implement RFC8446 section 8.1: by enforcing that 0-RTT is
1327
                // only possible if using stateful resumption
1328
0
                warn!("early_data with stateless resumption is not allowed");
1329
            }
1330
0
        }
1331
1332
0
        let t = HandshakeMessagePayload(HandshakePayload::NewSessionTicketTls13(payload));
1333
0
        trace!("sending new ticket {t:?} (stateless: {stateless})");
1334
0
        flight.add(t);
1335
1336
0
        Ok(())
1337
0
    }
1338
}
1339
1340
impl State<ServerConnectionData> for ExpectFinished {
1341
0
    fn handle<'m>(
1342
0
        mut self: Box<Self>,
1343
0
        cx: &mut ServerContext<'_>,
1344
0
        m: Message<'m>,
1345
0
    ) -> hs::NextStateOrError<'m>
1346
0
    where
1347
0
        Self: 'm,
1348
    {
1349
0
        let finished =
1350
0
            require_handshake_msg!(m, HandshakeType::Finished, HandshakePayload::Finished)?;
1351
1352
0
        let handshake_hash = self.transcript.current_hash();
1353
0
        let (key_schedule_before_finished, expect_verify_data) = self
1354
0
            .key_schedule
1355
0
            .sign_client_finish(&handshake_hash, cx.common);
1356
1357
0
        let fin = match ConstantTimeEq::ct_eq(expect_verify_data.as_ref(), finished.bytes()).into()
1358
        {
1359
0
            true => verify::FinishedMessageVerified::assertion(),
1360
            false => {
1361
0
                return Err(cx
1362
0
                    .common
1363
0
                    .send_fatal_alert(AlertDescription::DecryptError, Error::DecryptError));
1364
            }
1365
        };
1366
1367
        // Note: future derivations include Client Finished, but not the
1368
        // main application data keying.
1369
0
        self.transcript.add_message(&m);
1370
1371
0
        cx.common.check_aligned_handshake()?;
1372
1373
0
        let (key_schedule_traffic, resumption) =
1374
0
            key_schedule_before_finished.into_traffic(self.transcript.current_hash());
1375
1376
0
        let mut flight = HandshakeFlightTls13::new(&mut self.transcript);
1377
0
        for _ in 0..self.send_tickets {
1378
0
            Self::emit_ticket(&mut flight, self.suite, cx, &resumption, &self.config)?;
1379
        }
1380
0
        flight.finish(cx.common);
1381
1382
        // Application data may now flow, even if we have client auth enabled.
1383
0
        cx.common
1384
0
            .start_traffic(&mut cx.sendable_plaintext);
1385
1386
0
        Ok(match cx.common.is_quic() {
1387
0
            true => Box::new(ExpectQuicTraffic {
1388
0
                key_schedule: key_schedule_traffic,
1389
0
                _fin_verified: fin,
1390
0
            }),
1391
0
            false => Box::new(ExpectTraffic {
1392
0
                key_schedule: key_schedule_traffic,
1393
0
                _fin_verified: fin,
1394
0
            }),
1395
        })
1396
0
    }
1397
1398
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1399
0
        self
1400
0
    }
1401
}
1402
1403
// --- Process traffic ---
1404
struct ExpectTraffic {
1405
    key_schedule: KeyScheduleTraffic,
1406
    _fin_verified: verify::FinishedMessageVerified,
1407
}
1408
1409
impl ExpectTraffic {
1410
0
    fn handle_key_update(
1411
0
        &mut self,
1412
0
        common: &mut CommonState,
1413
0
        key_update_request: &KeyUpdateRequest,
1414
0
    ) -> Result<(), Error> {
1415
0
        if let Protocol::Quic = common.protocol {
1416
0
            return Err(common.send_fatal_alert(
1417
0
                AlertDescription::UnexpectedMessage,
1418
0
                PeerMisbehaved::KeyUpdateReceivedInQuicConnection,
1419
0
            ));
1420
0
        }
1421
1422
0
        common.check_aligned_handshake()?;
1423
1424
0
        if common.should_update_key(key_update_request)? {
1425
0
            self.key_schedule
1426
0
                .update_encrypter_and_notify(common);
1427
0
        }
1428
1429
        // Update our read-side keys.
1430
0
        self.key_schedule
1431
0
            .update_decrypter(common);
1432
0
        Ok(())
1433
0
    }
1434
}
1435
1436
impl State<ServerConnectionData> for ExpectTraffic {
1437
0
    fn handle<'m>(
1438
0
        mut self: Box<Self>,
1439
0
        cx: &mut ServerContext<'_>,
1440
0
        m: Message<'m>,
1441
0
    ) -> hs::NextStateOrError<'m>
1442
0
    where
1443
0
        Self: 'm,
1444
    {
1445
0
        match m.payload {
1446
0
            MessagePayload::ApplicationData(payload) => cx
1447
0
                .common
1448
0
                .take_received_plaintext(payload),
1449
            MessagePayload::Handshake {
1450
0
                parsed: HandshakeMessagePayload(HandshakePayload::KeyUpdate(key_update)),
1451
                ..
1452
0
            } => self.handle_key_update(cx.common, &key_update)?,
1453
0
            payload => {
1454
0
                return Err(inappropriate_handshake_message(
1455
0
                    &payload,
1456
0
                    &[ContentType::ApplicationData, ContentType::Handshake],
1457
0
                    &[HandshakeType::KeyUpdate],
1458
0
                ));
1459
            }
1460
        }
1461
1462
0
        Ok(self)
1463
0
    }
1464
1465
0
    fn export_keying_material(
1466
0
        &self,
1467
0
        output: &mut [u8],
1468
0
        label: &[u8],
1469
0
        context: Option<&[u8]>,
1470
0
    ) -> Result<(), Error> {
1471
0
        self.key_schedule
1472
0
            .export_keying_material(output, label, context)
1473
0
    }
1474
1475
0
    fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
1476
0
        self.key_schedule
1477
0
            .extract_secrets(Side::Server)
1478
0
    }
1479
1480
0
    fn send_key_update_request(&mut self, common: &mut CommonState) -> Result<(), Error> {
1481
0
        self.key_schedule
1482
0
            .request_key_update_and_update_encrypter(common)
1483
0
    }
1484
1485
0
    fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
1486
0
        Ok(self)
1487
0
    }
1488
1489
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1490
0
        self
1491
0
    }
1492
}
1493
1494
impl KernelState for ExpectTraffic {
1495
0
    fn update_secrets(&mut self, dir: Direction) -> Result<ConnectionTrafficSecrets, Error> {
1496
0
        self.key_schedule
1497
0
            .refresh_traffic_secret(match dir {
1498
0
                Direction::Transmit => Side::Server,
1499
0
                Direction::Receive => Side::Client,
1500
            })
1501
0
    }
1502
1503
0
    fn handle_new_session_ticket(
1504
0
        &mut self,
1505
0
        _cx: &mut KernelContext<'_>,
1506
0
        _message: &NewSessionTicketPayloadTls13,
1507
0
    ) -> Result<(), Error> {
1508
0
        unreachable!(
1509
            "server connections should never have handle_new_session_ticket called on them"
1510
        )
1511
    }
1512
}
1513
1514
struct ExpectQuicTraffic {
1515
    key_schedule: KeyScheduleTraffic,
1516
    _fin_verified: verify::FinishedMessageVerified,
1517
}
1518
1519
impl State<ServerConnectionData> for ExpectQuicTraffic {
1520
0
    fn handle<'m>(
1521
0
        self: Box<Self>,
1522
0
        _cx: &mut ServerContext<'_>,
1523
0
        m: Message<'m>,
1524
0
    ) -> hs::NextStateOrError<'m>
1525
0
    where
1526
0
        Self: 'm,
1527
    {
1528
        // reject all messages
1529
0
        Err(inappropriate_message(&m.payload, &[]))
1530
0
    }
1531
1532
0
    fn export_keying_material(
1533
0
        &self,
1534
0
        output: &mut [u8],
1535
0
        label: &[u8],
1536
0
        context: Option<&[u8]>,
1537
0
    ) -> Result<(), Error> {
1538
0
        self.key_schedule
1539
0
            .export_keying_material(output, label, context)
1540
0
    }
1541
1542
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1543
0
        self
1544
0
    }
1545
}
1546
1547
impl KernelState for ExpectQuicTraffic {
1548
0
    fn update_secrets(&mut self, _: Direction) -> Result<ConnectionTrafficSecrets, Error> {
1549
0
        Err(Error::General(
1550
0
            "QUIC connections do not support key updates".into(),
1551
0
        ))
1552
0
    }
1553
1554
0
    fn handle_new_session_ticket(
1555
0
        &mut self,
1556
0
        _cx: &mut KernelContext<'_>,
1557
0
        _message: &NewSessionTicketPayloadTls13,
1558
0
    ) -> Result<(), Error> {
1559
0
        unreachable!("handle_new_session_ticket should not be called for server-side connections")
1560
    }
1561
}