Coverage Report

Created: 2025-12-31 06:22

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