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/client/tls13.rs
Line
Count
Source
1
use alloc::boxed::Box;
2
use alloc::vec;
3
use alloc::vec::Vec;
4
5
use pki_types::ServerName;
6
use subtle::ConstantTimeEq;
7
8
use super::client_conn::ClientConnectionData;
9
use super::hs::{ClientContext, ClientHelloInput, ClientSessionValue};
10
use crate::check::inappropriate_handshake_message;
11
use crate::client::common::{ClientAuthDetails, ClientHelloDetails, ServerCertDetails};
12
use crate::client::ech::{self, EchState, EchStatus};
13
use crate::client::{ClientConfig, ClientSessionStore, hs};
14
use crate::common_state::{
15
    CommonState, HandshakeFlightTls13, HandshakeKind, KxState, Protocol, Side, State,
16
};
17
use crate::conn::ConnectionRandoms;
18
use crate::conn::kernel::{Direction, KernelContext, KernelState};
19
use crate::crypto::hash::Hash;
20
use crate::crypto::{ActiveKeyExchange, SharedSecret};
21
use crate::enums::{
22
    AlertDescription, ContentType, HandshakeType, ProtocolVersion, SignatureScheme,
23
};
24
use crate::error::{Error, InvalidMessage, PeerIncompatible, PeerMisbehaved};
25
use crate::hash_hs::{HandshakeHash, HandshakeHashBuffer};
26
use crate::log::{debug, trace, warn};
27
use crate::msgs::base::{Payload, PayloadU8};
28
use crate::msgs::ccs::ChangeCipherSpecPayload;
29
use crate::msgs::codec::{Codec, Reader};
30
use crate::msgs::enums::{ExtensionType, KeyUpdateRequest};
31
use crate::msgs::handshake::{
32
    CERTIFICATE_MAX_SIZE_LIMIT, CertificatePayloadTls13, ClientExtensions, EchConfigPayload,
33
    HandshakeMessagePayload, HandshakePayload, KeyShareEntry, NewSessionTicketPayloadTls13,
34
    PresharedKeyBinder, PresharedKeyIdentity, PresharedKeyOffer, ServerExtensions,
35
    ServerHelloPayload,
36
};
37
use crate::msgs::message::{Message, MessagePayload};
38
use crate::msgs::persist::{self, Retrieved};
39
use crate::sign::{CertifiedKey, Signer};
40
use crate::suites::PartiallyExtractedSecrets;
41
use crate::sync::Arc;
42
use crate::tls13::key_schedule::{
43
    KeyScheduleEarly, KeyScheduleHandshake, KeySchedulePreHandshake, KeyScheduleResumption,
44
    KeyScheduleTraffic,
45
};
46
use crate::tls13::{
47
    Tls13CipherSuite, construct_client_verify_message, construct_server_verify_message,
48
};
49
use crate::verify::{self, DigitallySignedStruct};
50
use crate::{ConnectionTrafficSecrets, KeyLog, compress, crypto};
51
52
// Extensions we expect in plaintext in the ServerHello.
53
static ALLOWED_PLAINTEXT_EXTS: &[ExtensionType] = &[
54
    ExtensionType::KeyShare,
55
    ExtensionType::PreSharedKey,
56
    ExtensionType::SupportedVersions,
57
];
58
59
// Only the intersection of things we offer, and those disallowed
60
// in TLS1.3
61
static DISALLOWED_TLS13_EXTS: &[ExtensionType] = &[
62
    ExtensionType::ECPointFormats,
63
    ExtensionType::SessionTicket,
64
    ExtensionType::RenegotiationInfo,
65
    ExtensionType::ExtendedMasterSecret,
66
];
67
68
/// `early_data_key_schedule` is `Some` if we sent the
69
/// "early_data" extension to the server.
70
0
pub(super) fn handle_server_hello(
71
0
    cx: &mut ClientContext<'_>,
72
0
    server_hello: &ServerHelloPayload,
73
0
    mut randoms: ConnectionRandoms,
74
0
    suite: &'static Tls13CipherSuite,
75
0
    mut transcript: HandshakeHash,
76
0
    early_data_key_schedule: Option<KeyScheduleEarly>,
77
0
    our_key_share: Box<dyn ActiveKeyExchange>,
78
0
    server_hello_msg: &Message<'_>,
79
0
    ech_state: Option<EchState>,
80
0
    input: ClientHelloInput,
81
0
) -> hs::NextStateOrError<'static> {
82
0
    validate_server_hello(cx.common, server_hello)?;
83
84
0
    let their_key_share = server_hello
85
0
        .key_share
86
0
        .as_ref()
87
0
        .ok_or_else(|| {
88
0
            cx.common.send_fatal_alert(
89
0
                AlertDescription::MissingExtension,
90
0
                PeerMisbehaved::MissingKeyShare,
91
            )
92
0
        })?;
93
94
    let ClientHelloInput {
95
0
        config,
96
0
        resuming,
97
0
        mut sent_tls13_fake_ccs,
98
0
        mut hello,
99
0
        server_name,
100
        ..
101
0
    } = input;
102
103
0
    let mut resuming_session = match resuming {
104
        Some(Retrieved {
105
0
            value: ClientSessionValue::Tls13(value),
106
            ..
107
0
        }) => Some(value),
108
0
        _ => None,
109
    };
110
111
0
    let our_key_share = KeyExchangeChoice::new(&config, cx, our_key_share, their_key_share)
112
0
        .map_err(|_| {
113
0
            cx.common.send_fatal_alert(
114
0
                AlertDescription::IllegalParameter,
115
0
                PeerMisbehaved::WrongGroupForKeyShare,
116
            )
117
0
        })?;
118
119
0
    let key_schedule_pre_handshake = match (server_hello.preshared_key, early_data_key_schedule) {
120
0
        (Some(selected_psk), Some(early_key_schedule)) => {
121
0
            match &resuming_session {
122
0
                Some(resuming) => {
123
0
                    let Some(resuming_suite) = suite.can_resume_from(resuming.suite()) else {
124
0
                        return Err({
125
0
                            cx.common.send_fatal_alert(
126
0
                                AlertDescription::IllegalParameter,
127
0
                                PeerMisbehaved::ResumptionOfferedWithIncompatibleCipherSuite,
128
0
                            )
129
0
                        });
130
                    };
131
132
                    // If the server varies the suite here, we will have encrypted early data with
133
                    // the wrong suite.
134
0
                    if cx.data.early_data.is_enabled() && resuming_suite != suite {
135
0
                        return Err({
136
0
                            cx.common.send_fatal_alert(
137
0
                                AlertDescription::IllegalParameter,
138
0
                                PeerMisbehaved::EarlyDataOfferedWithVariedCipherSuite,
139
0
                            )
140
0
                        });
141
0
                    }
142
143
0
                    if selected_psk != 0 {
144
0
                        return Err({
145
0
                            cx.common.send_fatal_alert(
146
0
                                AlertDescription::IllegalParameter,
147
0
                                PeerMisbehaved::SelectedInvalidPsk,
148
0
                            )
149
0
                        });
150
0
                    }
151
152
0
                    debug!("Resuming using PSK");
153
                    // The key schedule has been initialized and set in fill_in_psk_binder()
154
                }
155
                _ => {
156
0
                    return Err(PeerMisbehaved::SelectedUnofferedPsk.into());
157
                }
158
            }
159
0
            KeySchedulePreHandshake::from(early_key_schedule)
160
        }
161
        _ => {
162
0
            debug!("Not resuming");
163
            // Discard the early data key schedule.
164
0
            cx.data.early_data.rejected();
165
0
            cx.common.early_traffic = false;
166
0
            resuming_session.take();
167
0
            KeySchedulePreHandshake::new(suite)
168
        }
169
    };
170
171
0
    cx.common.kx_state.complete();
172
0
    let shared_secret = our_key_share
173
0
        .complete(&their_key_share.payload.0)
174
0
        .map_err(|err| {
175
0
            cx.common
176
0
                .send_fatal_alert(AlertDescription::IllegalParameter, err)
177
0
        })?;
178
179
0
    let mut key_schedule = key_schedule_pre_handshake.into_handshake(shared_secret);
180
181
    // If we have ECH state, check that the server accepted our offer.
182
0
    if let Some(ech_state) = ech_state {
183
        let Message {
184
            payload:
185
                MessagePayload::Handshake {
186
0
                    encoded: server_hello_encoded,
187
                    ..
188
                },
189
            ..
190
0
        } = &server_hello_msg
191
        else {
192
0
            unreachable!("ServerHello is a handshake message");
193
        };
194
0
        cx.data.ech_status = match ech_state.confirm_acceptance(
195
0
            &mut key_schedule,
196
0
            server_hello,
197
0
            server_hello_encoded,
198
0
            suite.common.hash_provider,
199
0
        )? {
200
            // The server accepted our ECH offer, so complete the inner transcript with the
201
            // server hello message, and switch the relevant state to the copies for the
202
            // inner client hello.
203
0
            Some(mut accepted) => {
204
0
                accepted
205
0
                    .transcript
206
0
                    .add_message(server_hello_msg);
207
0
                transcript = accepted.transcript;
208
0
                randoms.client = accepted.random.0;
209
0
                hello.sent_extensions = accepted.sent_extensions;
210
0
                EchStatus::Accepted
211
            }
212
            // The server rejected our ECH offer.
213
0
            None => EchStatus::Rejected,
214
        };
215
0
    }
216
217
    // Remember what KX group the server liked for next time.
218
0
    config
219
0
        .resumption
220
0
        .store
221
0
        .set_kx_hint(server_name.clone(), their_key_share.group);
222
223
    // If we change keying when a subsequent handshake message is being joined,
224
    // the two halves will have different record layer protections.  Disallow this.
225
0
    cx.common.check_aligned_handshake()?;
226
227
0
    let hash_at_client_recvd_server_hello = transcript.current_hash();
228
0
    let key_schedule = key_schedule.derive_client_handshake_secrets(
229
0
        cx.data.early_data.is_enabled(),
230
0
        hash_at_client_recvd_server_hello,
231
0
        suite,
232
0
        &*config.key_log,
233
0
        &randoms.client,
234
0
        cx.common,
235
    );
236
237
0
    emit_fake_ccs(&mut sent_tls13_fake_ccs, cx.common);
238
239
0
    Ok(Box::new(ExpectEncryptedExtensions {
240
0
        config,
241
0
        resuming_session,
242
0
        server_name,
243
0
        randoms,
244
0
        suite,
245
0
        transcript,
246
0
        key_schedule,
247
0
        hello,
248
0
    }))
249
0
}
250
251
enum KeyExchangeChoice {
252
    Whole(Box<dyn ActiveKeyExchange>),
253
    Component(Box<dyn ActiveKeyExchange>),
254
}
255
256
impl KeyExchangeChoice {
257
    /// Decide between `our_key_share` or `our_key_share.hybrid_component()`
258
    /// based on the selection of the server expressed in `their_key_share`.
259
0
    fn new(
260
0
        config: &Arc<ClientConfig>,
261
0
        cx: &mut ClientContext<'_>,
262
0
        our_key_share: Box<dyn ActiveKeyExchange>,
263
0
        their_key_share: &KeyShareEntry,
264
0
    ) -> Result<Self, ()> {
265
0
        if our_key_share.group() == their_key_share.group {
266
0
            return Ok(Self::Whole(our_key_share));
267
0
        }
268
269
0
        let (component_group, _) = our_key_share
270
0
            .hybrid_component()
271
0
            .ok_or(())?;
272
273
0
        if component_group != their_key_share.group {
274
0
            return Err(());
275
0
        }
276
277
        // correct the record for the benefit of accuracy of
278
        // `negotiated_key_exchange_group()`
279
0
        let actual_skxg = config
280
0
            .find_kx_group(component_group, ProtocolVersion::TLSv1_3)
281
0
            .ok_or(())?;
282
0
        cx.common.kx_state = KxState::Start(actual_skxg);
283
284
0
        Ok(Self::Component(our_key_share))
285
0
    }
286
287
0
    fn complete(self, peer_pub_key: &[u8]) -> Result<SharedSecret, Error> {
288
0
        match self {
289
0
            Self::Whole(akx) => akx.complete(peer_pub_key),
290
0
            Self::Component(akx) => akx.complete_hybrid_component(peer_pub_key),
291
        }
292
0
    }
293
}
294
295
0
fn validate_server_hello(
296
0
    common: &mut CommonState,
297
0
    server_hello: &ServerHelloPayload,
298
0
) -> Result<(), Error> {
299
0
    if !server_hello.only_contains(ALLOWED_PLAINTEXT_EXTS) {
300
0
        return Err(common.send_fatal_alert(
301
0
            AlertDescription::UnsupportedExtension,
302
0
            PeerMisbehaved::UnexpectedCleartextExtension,
303
0
        ));
304
0
    }
305
306
0
    Ok(())
307
0
}
308
309
0
pub(super) fn initial_key_share(
310
0
    config: &ClientConfig,
311
0
    server_name: &ServerName<'_>,
312
0
    kx_state: &mut KxState,
313
0
) -> Result<Box<dyn ActiveKeyExchange>, Error> {
314
0
    let group = config
315
0
        .resumption
316
0
        .store
317
0
        .kx_hint(server_name)
318
0
        .and_then(|group_name| config.find_kx_group(group_name, ProtocolVersion::TLSv1_3))
319
0
        .unwrap_or_else(|| {
320
0
            config
321
0
                .provider
322
0
                .kx_groups
323
0
                .iter()
324
0
                .copied()
325
0
                .next()
326
0
                .expect("No kx groups configured")
327
0
        });
328
329
0
    *kx_state = KxState::Start(group);
330
0
    group.start()
331
0
}
332
333
/// This implements the horrifying TLS1.3 hack where PSK binders have a
334
/// data dependency on the message they are contained within.
335
0
pub(super) fn fill_in_psk_binder(
336
0
    resuming: &persist::Tls13ClientSessionValue,
337
0
    transcript: &HandshakeHashBuffer,
338
0
    hmp: &mut HandshakeMessagePayload<'_>,
339
0
) -> KeyScheduleEarly {
340
    // We need to know the hash function of the suite we're trying to resume into.
341
0
    let suite = resuming.suite();
342
0
    let suite_hash = suite.common.hash_provider;
343
344
    // The binder is calculated over the clienthello, but doesn't include itself or its
345
    // length, or the length of its container.
346
0
    let binder_plaintext = hmp.encoding_for_binder_signing();
347
0
    let handshake_hash = transcript.hash_given(suite_hash, &binder_plaintext);
348
349
    // Run a fake key_schedule to simulate what the server will do if it chooses
350
    // to resume.
351
0
    let key_schedule = KeyScheduleEarly::new(suite, resuming.secret());
352
0
    let real_binder = key_schedule.resumption_psk_binder_key_and_sign_verify_data(&handshake_hash);
353
354
0
    if let HandshakePayload::ClientHello(ch) = &mut hmp.0 {
355
        if let Some(PresharedKeyOffer {
356
0
            binders,
357
0
            identities,
358
0
        }) = &mut ch.preshared_key_offer
359
        {
360
            // the caller of this function must have set up the desired identity, and a
361
            // matching (dummy) binder; or else the binder we compute here will be incorrect.
362
            // See `prepare_resumption()`.
363
0
            debug_assert_eq!(identities.len(), 1);
364
0
            debug_assert_eq!(binders.len(), 1);
365
0
            debug_assert_eq!(binders[0].as_ref().len(), real_binder.as_ref().len());
366
0
            binders[0] = PresharedKeyBinder::from(real_binder.as_ref().to_vec());
367
0
        }
368
0
    };
369
370
0
    key_schedule
371
0
}
372
373
0
pub(super) fn prepare_resumption(
374
0
    config: &ClientConfig,
375
0
    cx: &mut ClientContext<'_>,
376
0
    resuming_session: &Retrieved<&persist::Tls13ClientSessionValue>,
377
0
    exts: &mut ClientExtensions<'_>,
378
0
    doing_retry: bool,
379
0
) {
380
0
    let resuming_suite = resuming_session.suite();
381
0
    cx.common.suite = Some(resuming_suite.into());
382
    // The EarlyData extension MUST be supplied together with the
383
    // PreSharedKey extension.
384
0
    let max_early_data_size = resuming_session.max_early_data_size();
385
0
    if config.enable_early_data && max_early_data_size > 0 && !doing_retry {
386
0
        cx.data
387
0
            .early_data
388
0
            .enable(max_early_data_size as usize);
389
0
        exts.early_data_request = Some(());
390
0
    }
391
392
    // Finally, and only for TLS1.3 with a ticket resumption, include a binder
393
    // for our ticket.  This must go last.
394
    //
395
    // Include an empty binder. It gets filled in below because it depends on
396
    // the message it's contained in (!!!).
397
0
    let obfuscated_ticket_age = resuming_session.obfuscated_ticket_age();
398
399
0
    let binder_len = resuming_suite
400
0
        .common
401
0
        .hash_provider
402
0
        .output_len();
403
0
    let binder = vec![0u8; binder_len];
404
405
0
    let psk_identity =
406
0
        PresharedKeyIdentity::new(resuming_session.ticket().to_vec(), obfuscated_ticket_age);
407
0
    let psk_offer = PresharedKeyOffer::new(psk_identity, binder);
408
0
    exts.preshared_key_offer = Some(psk_offer);
409
0
}
410
411
0
pub(super) fn derive_early_traffic_secret(
412
0
    key_log: &dyn KeyLog,
413
0
    cx: &mut ClientContext<'_>,
414
0
    hash_alg: &'static dyn Hash,
415
0
    early_key_schedule: &KeyScheduleEarly,
416
0
    sent_tls13_fake_ccs: &mut bool,
417
0
    transcript_buffer: &HandshakeHashBuffer,
418
0
    client_random: &[u8; 32],
419
0
) {
420
    // For middlebox compatibility
421
0
    emit_fake_ccs(sent_tls13_fake_ccs, cx.common);
422
423
0
    let client_hello_hash = transcript_buffer.hash_given(hash_alg, &[]);
424
0
    early_key_schedule.client_early_traffic_secret(
425
0
        &client_hello_hash,
426
0
        key_log,
427
0
        client_random,
428
0
        cx.common,
429
    );
430
431
    // Now the client can send encrypted early data
432
0
    cx.common.early_traffic = true;
433
0
    trace!("Starting early data traffic");
434
0
}
435
436
0
pub(super) fn emit_fake_ccs(sent_tls13_fake_ccs: &mut bool, common: &mut CommonState) {
437
0
    if common.is_quic() {
438
0
        return;
439
0
    }
440
441
0
    if core::mem::replace(sent_tls13_fake_ccs, true) {
442
0
        return;
443
0
    }
444
445
0
    let m = Message {
446
0
        version: ProtocolVersion::TLSv1_2,
447
0
        payload: MessagePayload::ChangeCipherSpec(ChangeCipherSpecPayload {}),
448
0
    };
449
0
    common.send_msg(m, false);
450
0
}
451
452
0
fn validate_encrypted_extensions(
453
0
    common: &mut CommonState,
454
0
    hello: &ClientHelloDetails,
455
0
    exts: &ServerExtensions<'_>,
456
0
) -> Result<(), Error> {
457
0
    if hello.server_sent_unsolicited_extensions(exts, &[]) {
458
0
        return Err(common.send_fatal_alert(
459
0
            AlertDescription::UnsupportedExtension,
460
0
            PeerMisbehaved::UnsolicitedEncryptedExtension,
461
0
        ));
462
0
    }
463
464
0
    if exts.contains_any(ALLOWED_PLAINTEXT_EXTS) || exts.contains_any(DISALLOWED_TLS13_EXTS) {
465
0
        return Err(common.send_fatal_alert(
466
0
            AlertDescription::UnsupportedExtension,
467
0
            PeerMisbehaved::DisallowedEncryptedExtension,
468
0
        ));
469
0
    }
470
471
0
    Ok(())
472
0
}
473
474
struct ExpectEncryptedExtensions {
475
    config: Arc<ClientConfig>,
476
    resuming_session: Option<persist::Tls13ClientSessionValue>,
477
    server_name: ServerName<'static>,
478
    randoms: ConnectionRandoms,
479
    suite: &'static Tls13CipherSuite,
480
    transcript: HandshakeHash,
481
    key_schedule: KeyScheduleHandshake,
482
    hello: ClientHelloDetails,
483
}
484
485
impl State<ClientConnectionData> for ExpectEncryptedExtensions {
486
0
    fn handle<'m>(
487
0
        mut self: Box<Self>,
488
0
        cx: &mut ClientContext<'_>,
489
0
        m: Message<'m>,
490
0
    ) -> hs::NextStateOrError<'m>
491
0
    where
492
0
        Self: 'm,
493
    {
494
0
        let exts = require_handshake_msg!(
495
            m,
496
            HandshakeType::EncryptedExtensions,
497
            HandshakePayload::EncryptedExtensions
498
0
        )?;
499
0
        debug!("TLS1.3 encrypted extensions: {exts:?}");
500
0
        self.transcript.add_message(&m);
501
502
0
        validate_encrypted_extensions(cx.common, &self.hello, exts)?;
503
0
        hs::process_alpn_protocol(
504
0
            cx.common,
505
0
            &self.hello.alpn_protocols,
506
0
            exts.selected_protocol
507
0
                .as_ref()
508
0
                .map(|protocol| protocol.as_ref()),
509
0
            self.config.check_selected_alpn,
510
0
        )?;
511
0
        hs::process_client_cert_type_extension(
512
0
            cx.common,
513
0
            &self.config,
514
0
            exts.client_certificate_type.as_ref(),
515
0
        )?;
516
0
        hs::process_server_cert_type_extension(
517
0
            cx.common,
518
0
            &self.config,
519
0
            exts.server_certificate_type.as_ref(),
520
0
        )?;
521
522
0
        let ech_retry_configs = match (cx.data.ech_status, &exts.encrypted_client_hello_ack) {
523
            // If we didn't offer ECH, or ECH was accepted, but the server sent an ECH encrypted
524
            // extension with retry configs, we must error.
525
            (EchStatus::NotOffered | EchStatus::Accepted, Some(_)) => {
526
0
                return Err(cx.common.send_fatal_alert(
527
0
                    AlertDescription::UnsupportedExtension,
528
0
                    PeerMisbehaved::UnsolicitedEchExtension,
529
0
                ));
530
            }
531
            // If we offered ECH, and it was rejected, store the retry configs (if any) from
532
            // the server's ECH extension. We will return them in an error produced at the end
533
            // of the handshake.
534
0
            (EchStatus::Rejected, ext) => ext
535
0
                .as_ref()
536
0
                .map(|ext| ext.retry_configs.to_vec()),
537
0
            _ => None,
538
        };
539
540
        // QUIC transport parameters
541
0
        if cx.common.is_quic() {
542
0
            match exts
543
0
                .transport_parameters
544
0
                .as_ref()
545
0
                .or(exts.transport_parameters_draft.as_ref())
546
            {
547
0
                Some(params) => cx.common.quic.params = Some(params.clone().into_vec()),
548
                None => {
549
0
                    return Err(cx
550
0
                        .common
551
0
                        .missing_extension(PeerMisbehaved::MissingQuicTransportParameters));
552
                }
553
            }
554
0
        }
555
556
0
        match self.resuming_session {
557
0
            Some(resuming_session) => {
558
0
                let was_early_traffic = cx.common.early_traffic;
559
0
                if was_early_traffic {
560
0
                    match exts.early_data_ack {
561
0
                        Some(()) => cx.data.early_data.accepted(),
562
0
                        None => {
563
0
                            cx.data.early_data.rejected();
564
0
                            cx.common.early_traffic = false;
565
0
                        }
566
                    }
567
0
                }
568
569
0
                if was_early_traffic && !cx.common.early_traffic {
570
0
                    // If no early traffic, set the encryption key for handshakes
571
0
                    self.key_schedule
572
0
                        .set_handshake_encrypter(cx.common);
573
0
                }
574
575
0
                cx.common.peer_certificates = Some(
576
0
                    resuming_session
577
0
                        .server_cert_chain()
578
0
                        .clone(),
579
0
                );
580
0
                cx.common.handshake_kind = Some(HandshakeKind::Resumed);
581
582
                // We *don't* reverify the certificate chain here: resumption is a
583
                // continuation of the previous session in terms of security policy.
584
0
                let cert_verified = verify::ServerCertVerified::assertion();
585
0
                let sig_verified = verify::HandshakeSignatureValid::assertion();
586
0
                Ok(Box::new(ExpectFinished {
587
0
                    config: self.config,
588
0
                    server_name: self.server_name,
589
0
                    randoms: self.randoms,
590
0
                    suite: self.suite,
591
0
                    transcript: self.transcript,
592
0
                    key_schedule: self.key_schedule,
593
0
                    client_auth: None,
594
0
                    cert_verified,
595
0
                    sig_verified,
596
0
                    ech_retry_configs,
597
0
                }))
598
            }
599
            _ => {
600
0
                if exts.early_data_ack.is_some() {
601
0
                    return Err(PeerMisbehaved::EarlyDataExtensionWithoutResumption.into());
602
0
                }
603
0
                cx.common
604
0
                    .handshake_kind
605
0
                    .get_or_insert(HandshakeKind::Full);
606
607
0
                Ok(if self.hello.offered_cert_compression {
608
0
                    Box::new(ExpectCertificateOrCompressedCertificateOrCertReq {
609
0
                        config: self.config,
610
0
                        server_name: self.server_name,
611
0
                        randoms: self.randoms,
612
0
                        suite: self.suite,
613
0
                        transcript: self.transcript,
614
0
                        key_schedule: self.key_schedule,
615
0
                        ech_retry_configs,
616
0
                    })
617
                } else {
618
0
                    Box::new(ExpectCertificateOrCertReq {
619
0
                        config: self.config,
620
0
                        server_name: self.server_name,
621
0
                        randoms: self.randoms,
622
0
                        suite: self.suite,
623
0
                        transcript: self.transcript,
624
0
                        key_schedule: self.key_schedule,
625
0
                        ech_retry_configs,
626
0
                    })
627
                })
628
            }
629
        }
630
0
    }
631
632
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
633
0
        self
634
0
    }
635
}
636
637
struct ExpectCertificateOrCompressedCertificateOrCertReq {
638
    config: Arc<ClientConfig>,
639
    server_name: ServerName<'static>,
640
    randoms: ConnectionRandoms,
641
    suite: &'static Tls13CipherSuite,
642
    transcript: HandshakeHash,
643
    key_schedule: KeyScheduleHandshake,
644
    ech_retry_configs: Option<Vec<EchConfigPayload>>,
645
}
646
647
impl State<ClientConnectionData> for ExpectCertificateOrCompressedCertificateOrCertReq {
648
0
    fn handle<'m>(
649
0
        self: Box<Self>,
650
0
        cx: &mut ClientContext<'_>,
651
0
        m: Message<'m>,
652
0
    ) -> hs::NextStateOrError<'m>
653
0
    where
654
0
        Self: 'm,
655
    {
656
0
        match m.payload {
657
            MessagePayload::Handshake {
658
                parsed: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
659
                ..
660
0
            } => Box::new(ExpectCertificate {
661
0
                config: self.config,
662
0
                server_name: self.server_name,
663
0
                randoms: self.randoms,
664
0
                suite: self.suite,
665
0
                transcript: self.transcript,
666
0
                key_schedule: self.key_schedule,
667
0
                client_auth: None,
668
0
                message_already_in_transcript: false,
669
0
                ech_retry_configs: self.ech_retry_configs,
670
0
            })
671
0
            .handle(cx, m),
672
            MessagePayload::Handshake {
673
                parsed: HandshakeMessagePayload(HandshakePayload::CompressedCertificate(..)),
674
                ..
675
0
            } => Box::new(ExpectCompressedCertificate {
676
0
                config: self.config,
677
0
                server_name: self.server_name,
678
0
                randoms: self.randoms,
679
0
                suite: self.suite,
680
0
                transcript: self.transcript,
681
0
                key_schedule: self.key_schedule,
682
0
                client_auth: None,
683
0
                ech_retry_configs: self.ech_retry_configs,
684
0
            })
685
0
            .handle(cx, m),
686
            MessagePayload::Handshake {
687
                parsed: HandshakeMessagePayload(HandshakePayload::CertificateRequestTls13(..)),
688
                ..
689
0
            } => Box::new(ExpectCertificateRequest {
690
0
                config: self.config,
691
0
                server_name: self.server_name,
692
0
                randoms: self.randoms,
693
0
                suite: self.suite,
694
0
                transcript: self.transcript,
695
0
                key_schedule: self.key_schedule,
696
0
                offered_cert_compression: true,
697
0
                ech_retry_configs: self.ech_retry_configs,
698
0
            })
699
0
            .handle(cx, m),
700
0
            payload => Err(inappropriate_handshake_message(
701
0
                &payload,
702
0
                &[ContentType::Handshake],
703
0
                &[
704
0
                    HandshakeType::Certificate,
705
0
                    HandshakeType::CertificateRequest,
706
0
                    HandshakeType::CompressedCertificate,
707
0
                ],
708
0
            )),
709
        }
710
0
    }
711
712
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
713
0
        self
714
0
    }
715
}
716
717
struct ExpectCertificateOrCompressedCertificate {
718
    config: Arc<ClientConfig>,
719
    server_name: ServerName<'static>,
720
    randoms: ConnectionRandoms,
721
    suite: &'static Tls13CipherSuite,
722
    transcript: HandshakeHash,
723
    key_schedule: KeyScheduleHandshake,
724
    client_auth: Option<ClientAuthDetails>,
725
    ech_retry_configs: Option<Vec<EchConfigPayload>>,
726
}
727
728
impl State<ClientConnectionData> for ExpectCertificateOrCompressedCertificate {
729
0
    fn handle<'m>(
730
0
        self: Box<Self>,
731
0
        cx: &mut ClientContext<'_>,
732
0
        m: Message<'m>,
733
0
    ) -> hs::NextStateOrError<'m>
734
0
    where
735
0
        Self: 'm,
736
    {
737
0
        match m.payload {
738
            MessagePayload::Handshake {
739
                parsed: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
740
                ..
741
0
            } => Box::new(ExpectCertificate {
742
0
                config: self.config,
743
0
                server_name: self.server_name,
744
0
                randoms: self.randoms,
745
0
                suite: self.suite,
746
0
                transcript: self.transcript,
747
0
                key_schedule: self.key_schedule,
748
0
                client_auth: self.client_auth,
749
0
                message_already_in_transcript: false,
750
0
                ech_retry_configs: self.ech_retry_configs,
751
0
            })
752
0
            .handle(cx, m),
753
            MessagePayload::Handshake {
754
                parsed: HandshakeMessagePayload(HandshakePayload::CompressedCertificate(..)),
755
                ..
756
0
            } => Box::new(ExpectCompressedCertificate {
757
0
                config: self.config,
758
0
                server_name: self.server_name,
759
0
                randoms: self.randoms,
760
0
                suite: self.suite,
761
0
                transcript: self.transcript,
762
0
                key_schedule: self.key_schedule,
763
0
                client_auth: self.client_auth,
764
0
                ech_retry_configs: self.ech_retry_configs,
765
0
            })
766
0
            .handle(cx, m),
767
0
            payload => Err(inappropriate_handshake_message(
768
0
                &payload,
769
0
                &[ContentType::Handshake],
770
0
                &[
771
0
                    HandshakeType::Certificate,
772
0
                    HandshakeType::CompressedCertificate,
773
0
                ],
774
0
            )),
775
        }
776
0
    }
777
778
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
779
0
        self
780
0
    }
781
}
782
783
struct ExpectCertificateOrCertReq {
784
    config: Arc<ClientConfig>,
785
    server_name: ServerName<'static>,
786
    randoms: ConnectionRandoms,
787
    suite: &'static Tls13CipherSuite,
788
    transcript: HandshakeHash,
789
    key_schedule: KeyScheduleHandshake,
790
    ech_retry_configs: Option<Vec<EchConfigPayload>>,
791
}
792
793
impl State<ClientConnectionData> for ExpectCertificateOrCertReq {
794
0
    fn handle<'m>(
795
0
        self: Box<Self>,
796
0
        cx: &mut ClientContext<'_>,
797
0
        m: Message<'m>,
798
0
    ) -> hs::NextStateOrError<'m>
799
0
    where
800
0
        Self: 'm,
801
    {
802
0
        match m.payload {
803
            MessagePayload::Handshake {
804
                parsed: HandshakeMessagePayload(HandshakePayload::CertificateTls13(..)),
805
                ..
806
0
            } => Box::new(ExpectCertificate {
807
0
                config: self.config,
808
0
                server_name: self.server_name,
809
0
                randoms: self.randoms,
810
0
                suite: self.suite,
811
0
                transcript: self.transcript,
812
0
                key_schedule: self.key_schedule,
813
0
                client_auth: None,
814
0
                message_already_in_transcript: false,
815
0
                ech_retry_configs: self.ech_retry_configs,
816
0
            })
817
0
            .handle(cx, m),
818
            MessagePayload::Handshake {
819
                parsed: HandshakeMessagePayload(HandshakePayload::CertificateRequestTls13(..)),
820
                ..
821
0
            } => Box::new(ExpectCertificateRequest {
822
0
                config: self.config,
823
0
                server_name: self.server_name,
824
0
                randoms: self.randoms,
825
0
                suite: self.suite,
826
0
                transcript: self.transcript,
827
0
                key_schedule: self.key_schedule,
828
0
                offered_cert_compression: false,
829
0
                ech_retry_configs: self.ech_retry_configs,
830
0
            })
831
0
            .handle(cx, m),
832
0
            payload => Err(inappropriate_handshake_message(
833
0
                &payload,
834
0
                &[ContentType::Handshake],
835
0
                &[
836
0
                    HandshakeType::Certificate,
837
0
                    HandshakeType::CertificateRequest,
838
0
                ],
839
0
            )),
840
        }
841
0
    }
842
843
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
844
0
        self
845
0
    }
846
}
847
848
// TLS1.3 version of CertificateRequest handling.  We then move to expecting the server
849
// Certificate. Unfortunately the CertificateRequest type changed in an annoying way
850
// in TLS1.3.
851
struct ExpectCertificateRequest {
852
    config: Arc<ClientConfig>,
853
    server_name: ServerName<'static>,
854
    randoms: ConnectionRandoms,
855
    suite: &'static Tls13CipherSuite,
856
    transcript: HandshakeHash,
857
    key_schedule: KeyScheduleHandshake,
858
    offered_cert_compression: bool,
859
    ech_retry_configs: Option<Vec<EchConfigPayload>>,
860
}
861
862
impl State<ClientConnectionData> for ExpectCertificateRequest {
863
0
    fn handle<'m>(
864
0
        mut self: Box<Self>,
865
0
        cx: &mut ClientContext<'_>,
866
0
        m: Message<'m>,
867
0
    ) -> hs::NextStateOrError<'m>
868
0
    where
869
0
        Self: 'm,
870
    {
871
0
        let certreq = &require_handshake_msg!(
872
            m,
873
            HandshakeType::CertificateRequest,
874
            HandshakePayload::CertificateRequestTls13
875
0
        )?;
876
0
        self.transcript.add_message(&m);
877
0
        debug!("Got CertificateRequest {certreq:?}");
878
879
        // Fortunately the problems here in TLS1.2 and prior are corrected in
880
        // TLS1.3.
881
882
        // Must be empty during handshake.
883
0
        if !certreq.context.0.is_empty() {
884
0
            warn!("Server sent non-empty certreq context");
885
0
            return Err(cx.common.send_fatal_alert(
886
0
                AlertDescription::DecodeError,
887
0
                InvalidMessage::InvalidCertRequest,
888
0
            ));
889
0
        }
890
891
0
        let compat_sigschemes = certreq
892
0
            .extensions
893
0
            .signature_algorithms
894
0
            .as_deref()
895
0
            .unwrap_or_default()
896
0
            .iter()
897
0
            .cloned()
898
0
            .filter(SignatureScheme::supported_in_tls13)
899
0
            .collect::<Vec<SignatureScheme>>();
900
901
0
        if compat_sigschemes.is_empty() {
902
0
            return Err(cx.common.send_fatal_alert(
903
0
                AlertDescription::HandshakeFailure,
904
0
                PeerIncompatible::NoCertificateRequestSignatureSchemesInCommon,
905
0
            ));
906
0
        }
907
908
0
        let compat_compressor = certreq
909
0
            .extensions
910
0
            .certificate_compression_algorithms
911
0
            .as_deref()
912
0
            .and_then(|offered| {
913
0
                self.config
914
0
                    .cert_compressors
915
0
                    .iter()
916
0
                    .find(|compressor| offered.contains(&compressor.algorithm()))
917
0
            })
918
0
            .cloned();
919
920
0
        let client_auth = ClientAuthDetails::resolve(
921
0
            self.config
922
0
                .client_auth_cert_resolver
923
0
                .as_ref(),
924
0
            certreq
925
0
                .extensions
926
0
                .authority_names
927
0
                .as_deref(),
928
0
            &compat_sigschemes,
929
0
            Some(certreq.context.0.clone()),
930
0
            compat_compressor,
931
        );
932
933
0
        Ok(if self.offered_cert_compression {
934
0
            Box::new(ExpectCertificateOrCompressedCertificate {
935
0
                config: self.config,
936
0
                server_name: self.server_name,
937
0
                randoms: self.randoms,
938
0
                suite: self.suite,
939
0
                transcript: self.transcript,
940
0
                key_schedule: self.key_schedule,
941
0
                client_auth: Some(client_auth),
942
0
                ech_retry_configs: self.ech_retry_configs,
943
0
            })
944
        } else {
945
0
            Box::new(ExpectCertificate {
946
0
                config: self.config,
947
0
                server_name: self.server_name,
948
0
                randoms: self.randoms,
949
0
                suite: self.suite,
950
0
                transcript: self.transcript,
951
0
                key_schedule: self.key_schedule,
952
0
                client_auth: Some(client_auth),
953
0
                message_already_in_transcript: false,
954
0
                ech_retry_configs: self.ech_retry_configs,
955
0
            })
956
        })
957
0
    }
958
959
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
960
0
        self
961
0
    }
962
}
963
964
struct ExpectCompressedCertificate {
965
    config: Arc<ClientConfig>,
966
    server_name: ServerName<'static>,
967
    randoms: ConnectionRandoms,
968
    suite: &'static Tls13CipherSuite,
969
    transcript: HandshakeHash,
970
    key_schedule: KeyScheduleHandshake,
971
    client_auth: Option<ClientAuthDetails>,
972
    ech_retry_configs: Option<Vec<EchConfigPayload>>,
973
}
974
975
impl State<ClientConnectionData> for ExpectCompressedCertificate {
976
0
    fn handle<'m>(
977
0
        mut self: Box<Self>,
978
0
        cx: &mut ClientContext<'_>,
979
0
        m: Message<'m>,
980
0
    ) -> hs::NextStateOrError<'m>
981
0
    where
982
0
        Self: 'm,
983
    {
984
0
        self.transcript.add_message(&m);
985
0
        let compressed_cert = require_handshake_msg_move!(
986
            m,
987
            HandshakeType::CompressedCertificate,
988
            HandshakePayload::CompressedCertificate
989
0
        )?;
990
991
0
        let selected_decompressor = self
992
0
            .config
993
0
            .cert_decompressors
994
0
            .iter()
995
0
            .find(|item| item.algorithm() == compressed_cert.alg);
996
997
0
        let Some(decompressor) = selected_decompressor else {
998
0
            return Err(cx.common.send_fatal_alert(
999
0
                AlertDescription::BadCertificate,
1000
0
                PeerMisbehaved::SelectedUnofferedCertCompression,
1001
0
            ));
1002
        };
1003
1004
0
        if compressed_cert.uncompressed_len as usize > CERTIFICATE_MAX_SIZE_LIMIT {
1005
0
            return Err(cx.common.send_fatal_alert(
1006
0
                AlertDescription::BadCertificate,
1007
0
                InvalidMessage::MessageTooLarge,
1008
0
            ));
1009
0
        }
1010
1011
0
        let mut decompress_buffer = vec![0u8; compressed_cert.uncompressed_len as usize];
1012
        if let Err(compress::DecompressionFailed) =
1013
0
            decompressor.decompress(compressed_cert.compressed.0.bytes(), &mut decompress_buffer)
1014
        {
1015
0
            return Err(cx.common.send_fatal_alert(
1016
0
                AlertDescription::BadCertificate,
1017
0
                PeerMisbehaved::InvalidCertCompression,
1018
0
            ));
1019
0
        }
1020
1021
0
        let cert_payload =
1022
0
            match CertificatePayloadTls13::read(&mut Reader::init(&decompress_buffer)) {
1023
0
                Ok(cm) => cm,
1024
0
                Err(err) => {
1025
0
                    return Err(cx
1026
0
                        .common
1027
0
                        .send_fatal_alert(AlertDescription::BadCertificate, err));
1028
                }
1029
            };
1030
0
        trace!(
1031
0
            "Server certificate decompressed using {:?} ({} bytes -> {})",
1032
            compressed_cert.alg,
1033
0
            compressed_cert
1034
0
                .compressed
1035
0
                .0
1036
0
                .bytes()
1037
0
                .len(),
1038
            compressed_cert.uncompressed_len,
1039
        );
1040
1041
0
        let m = Message {
1042
0
            version: ProtocolVersion::TLSv1_3,
1043
0
            payload: MessagePayload::handshake(HandshakeMessagePayload(
1044
0
                HandshakePayload::CertificateTls13(cert_payload.into_owned()),
1045
0
            )),
1046
0
        };
1047
1048
0
        Box::new(ExpectCertificate {
1049
0
            config: self.config,
1050
0
            server_name: self.server_name,
1051
0
            randoms: self.randoms,
1052
0
            suite: self.suite,
1053
0
            transcript: self.transcript,
1054
0
            key_schedule: self.key_schedule,
1055
0
            client_auth: self.client_auth,
1056
0
            message_already_in_transcript: true,
1057
0
            ech_retry_configs: self.ech_retry_configs,
1058
0
        })
1059
0
        .handle(cx, m)
1060
0
    }
1061
1062
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1063
0
        self
1064
0
    }
1065
}
1066
1067
struct ExpectCertificate {
1068
    config: Arc<ClientConfig>,
1069
    server_name: ServerName<'static>,
1070
    randoms: ConnectionRandoms,
1071
    suite: &'static Tls13CipherSuite,
1072
    transcript: HandshakeHash,
1073
    key_schedule: KeyScheduleHandshake,
1074
    client_auth: Option<ClientAuthDetails>,
1075
    message_already_in_transcript: bool,
1076
    ech_retry_configs: Option<Vec<EchConfigPayload>>,
1077
}
1078
1079
impl State<ClientConnectionData> for ExpectCertificate {
1080
0
    fn handle<'m>(
1081
0
        mut self: Box<Self>,
1082
0
        cx: &mut ClientContext<'_>,
1083
0
        m: Message<'m>,
1084
0
    ) -> hs::NextStateOrError<'m>
1085
0
    where
1086
0
        Self: 'm,
1087
    {
1088
0
        if !self.message_already_in_transcript {
1089
0
            self.transcript.add_message(&m);
1090
0
        }
1091
0
        let cert_chain = require_handshake_msg_move!(
1092
            m,
1093
            HandshakeType::Certificate,
1094
            HandshakePayload::CertificateTls13
1095
0
        )?;
1096
1097
        // This is only non-empty for client auth.
1098
0
        if !cert_chain.context.0.is_empty() {
1099
0
            return Err(cx.common.send_fatal_alert(
1100
0
                AlertDescription::DecodeError,
1101
0
                InvalidMessage::InvalidCertRequest,
1102
0
            ));
1103
0
        }
1104
1105
0
        let end_entity_ocsp = cert_chain.end_entity_ocsp().to_vec();
1106
0
        let server_cert = ServerCertDetails::new(
1107
0
            cert_chain
1108
0
                .into_certificate_chain()
1109
0
                .into_owned(),
1110
0
            end_entity_ocsp,
1111
        );
1112
1113
0
        Ok(Box::new(ExpectCertificateVerify {
1114
0
            config: self.config,
1115
0
            server_name: self.server_name,
1116
0
            randoms: self.randoms,
1117
0
            suite: self.suite,
1118
0
            transcript: self.transcript,
1119
0
            key_schedule: self.key_schedule,
1120
0
            server_cert,
1121
0
            client_auth: self.client_auth,
1122
0
            ech_retry_configs: self.ech_retry_configs,
1123
0
        }))
1124
0
    }
1125
1126
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1127
0
        self
1128
0
    }
1129
}
1130
1131
// --- TLS1.3 CertificateVerify ---
1132
struct ExpectCertificateVerify<'a> {
1133
    config: Arc<ClientConfig>,
1134
    server_name: ServerName<'static>,
1135
    randoms: ConnectionRandoms,
1136
    suite: &'static Tls13CipherSuite,
1137
    transcript: HandshakeHash,
1138
    key_schedule: KeyScheduleHandshake,
1139
    server_cert: ServerCertDetails<'a>,
1140
    client_auth: Option<ClientAuthDetails>,
1141
    ech_retry_configs: Option<Vec<EchConfigPayload>>,
1142
}
1143
1144
impl State<ClientConnectionData> for ExpectCertificateVerify<'_> {
1145
0
    fn handle<'m>(
1146
0
        mut self: Box<Self>,
1147
0
        cx: &mut ClientContext<'_>,
1148
0
        m: Message<'m>,
1149
0
    ) -> hs::NextStateOrError<'m>
1150
0
    where
1151
0
        Self: 'm,
1152
    {
1153
0
        let cert_verify = require_handshake_msg!(
1154
            m,
1155
            HandshakeType::CertificateVerify,
1156
            HandshakePayload::CertificateVerify
1157
0
        )?;
1158
1159
0
        trace!("Server cert is {:?}", self.server_cert.cert_chain);
1160
1161
        // 1. Verify the certificate chain.
1162
0
        let (end_entity, intermediates) = self
1163
0
            .server_cert
1164
0
            .cert_chain
1165
0
            .split_first()
1166
0
            .ok_or(Error::NoCertificatesPresented)?;
1167
1168
0
        let now = self.config.current_time()?;
1169
1170
0
        let cert_verified = self
1171
0
            .config
1172
0
            .verifier
1173
0
            .verify_server_cert(
1174
0
                end_entity,
1175
0
                intermediates,
1176
0
                &self.server_name,
1177
0
                &self.server_cert.ocsp_response,
1178
0
                now,
1179
0
            )
1180
0
            .map_err(|err| {
1181
0
                cx.common
1182
0
                    .send_cert_verify_error_alert(err)
1183
0
            })?;
1184
1185
        // 2. Verify their signature on the handshake.
1186
0
        let handshake_hash = self.transcript.current_hash();
1187
0
        let sig_verified = self
1188
0
            .config
1189
0
            .verifier
1190
0
            .verify_tls13_signature(
1191
0
                construct_server_verify_message(&handshake_hash).as_ref(),
1192
0
                end_entity,
1193
0
                cert_verify,
1194
0
            )
1195
0
            .map_err(|err| {
1196
0
                cx.common
1197
0
                    .send_cert_verify_error_alert(err)
1198
0
            })?;
1199
1200
0
        cx.common.peer_certificates = Some(self.server_cert.cert_chain.into_owned());
1201
0
        self.transcript.add_message(&m);
1202
1203
0
        Ok(Box::new(ExpectFinished {
1204
0
            config: self.config,
1205
0
            server_name: self.server_name,
1206
0
            randoms: self.randoms,
1207
0
            suite: self.suite,
1208
0
            transcript: self.transcript,
1209
0
            key_schedule: self.key_schedule,
1210
0
            client_auth: self.client_auth,
1211
0
            cert_verified,
1212
0
            sig_verified,
1213
0
            ech_retry_configs: self.ech_retry_configs,
1214
0
        }))
1215
0
    }
1216
1217
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1218
0
        Box::new(ExpectCertificateVerify {
1219
0
            config: self.config,
1220
0
            server_name: self.server_name,
1221
0
            randoms: self.randoms,
1222
0
            suite: self.suite,
1223
0
            transcript: self.transcript,
1224
0
            key_schedule: self.key_schedule,
1225
0
            server_cert: self.server_cert.into_owned(),
1226
0
            client_auth: self.client_auth,
1227
0
            ech_retry_configs: self.ech_retry_configs,
1228
0
        })
1229
0
    }
1230
}
1231
1232
0
fn emit_compressed_certificate_tls13(
1233
0
    flight: &mut HandshakeFlightTls13<'_>,
1234
0
    certkey: &CertifiedKey,
1235
0
    auth_context: Option<Vec<u8>>,
1236
0
    compressor: &dyn compress::CertCompressor,
1237
0
    config: &ClientConfig,
1238
0
) {
1239
0
    let mut cert_payload = CertificatePayloadTls13::new(certkey.cert.iter(), None);
1240
0
    cert_payload.context = PayloadU8::new(auth_context.clone().unwrap_or_default());
1241
1242
0
    let Ok(compressed) = config
1243
0
        .cert_compression_cache
1244
0
        .compression_for(compressor, &cert_payload)
1245
    else {
1246
0
        return emit_certificate_tls13(flight, Some(certkey), auth_context);
1247
    };
1248
1249
0
    flight.add(HandshakeMessagePayload(
1250
0
        HandshakePayload::CompressedCertificate(compressed.compressed_cert_payload()),
1251
0
    ));
1252
0
}
1253
1254
0
fn emit_certificate_tls13(
1255
0
    flight: &mut HandshakeFlightTls13<'_>,
1256
0
    certkey: Option<&CertifiedKey>,
1257
0
    auth_context: Option<Vec<u8>>,
1258
0
) {
1259
0
    let certs = certkey
1260
0
        .map(|ck| ck.cert.as_ref())
1261
0
        .unwrap_or(&[][..]);
1262
0
    let mut cert_payload = CertificatePayloadTls13::new(certs.iter(), None);
1263
0
    cert_payload.context = PayloadU8::new(auth_context.unwrap_or_default());
1264
1265
0
    flight.add(HandshakeMessagePayload(HandshakePayload::CertificateTls13(
1266
0
        cert_payload,
1267
0
    )));
1268
0
}
1269
1270
0
fn emit_certverify_tls13(
1271
0
    flight: &mut HandshakeFlightTls13<'_>,
1272
0
    signer: &dyn Signer,
1273
0
) -> Result<(), Error> {
1274
0
    let message = construct_client_verify_message(&flight.transcript.current_hash());
1275
1276
0
    let scheme = signer.scheme();
1277
0
    let sig = signer.sign(message.as_ref())?;
1278
0
    let dss = DigitallySignedStruct::new(scheme, sig);
1279
1280
0
    flight.add(HandshakeMessagePayload(
1281
0
        HandshakePayload::CertificateVerify(dss),
1282
0
    ));
1283
0
    Ok(())
1284
0
}
1285
1286
0
fn emit_finished_tls13(flight: &mut HandshakeFlightTls13<'_>, verify_data: &crypto::hmac::Tag) {
1287
0
    let verify_data_payload = Payload::new(verify_data.as_ref());
1288
1289
0
    flight.add(HandshakeMessagePayload(HandshakePayload::Finished(
1290
0
        verify_data_payload,
1291
0
    )));
1292
0
}
1293
1294
0
fn emit_end_of_early_data_tls13(transcript: &mut HandshakeHash, common: &mut CommonState) {
1295
0
    if common.is_quic() {
1296
0
        return;
1297
0
    }
1298
1299
0
    let m = Message {
1300
0
        version: ProtocolVersion::TLSv1_3,
1301
0
        payload: MessagePayload::handshake(HandshakeMessagePayload(
1302
0
            HandshakePayload::EndOfEarlyData,
1303
0
        )),
1304
0
    };
1305
1306
0
    transcript.add_message(&m);
1307
0
    common.send_msg(m, true);
1308
0
}
1309
1310
struct ExpectFinished {
1311
    config: Arc<ClientConfig>,
1312
    server_name: ServerName<'static>,
1313
    randoms: ConnectionRandoms,
1314
    suite: &'static Tls13CipherSuite,
1315
    transcript: HandshakeHash,
1316
    key_schedule: KeyScheduleHandshake,
1317
    client_auth: Option<ClientAuthDetails>,
1318
    cert_verified: verify::ServerCertVerified,
1319
    sig_verified: verify::HandshakeSignatureValid,
1320
    ech_retry_configs: Option<Vec<EchConfigPayload>>,
1321
}
1322
1323
impl State<ClientConnectionData> for ExpectFinished {
1324
0
    fn handle<'m>(
1325
0
        self: Box<Self>,
1326
0
        cx: &mut ClientContext<'_>,
1327
0
        m: Message<'m>,
1328
0
    ) -> hs::NextStateOrError<'m>
1329
0
    where
1330
0
        Self: 'm,
1331
    {
1332
0
        let mut st = *self;
1333
0
        let finished =
1334
0
            require_handshake_msg!(m, HandshakeType::Finished, HandshakePayload::Finished)?;
1335
1336
0
        let handshake_hash = st.transcript.current_hash();
1337
0
        let expect_verify_data = st
1338
0
            .key_schedule
1339
0
            .sign_server_finish(&handshake_hash);
1340
1341
0
        let fin = match ConstantTimeEq::ct_eq(expect_verify_data.as_ref(), finished.bytes()).into()
1342
        {
1343
0
            true => verify::FinishedMessageVerified::assertion(),
1344
            false => {
1345
0
                return Err(cx
1346
0
                    .common
1347
0
                    .send_fatal_alert(AlertDescription::DecryptError, Error::DecryptError));
1348
            }
1349
        };
1350
1351
0
        st.transcript.add_message(&m);
1352
1353
0
        let hash_after_handshake = st.transcript.current_hash();
1354
        /* The EndOfEarlyData message to server is still encrypted with early data keys,
1355
         * but appears in the transcript after the server Finished. */
1356
0
        if cx.common.early_traffic {
1357
0
            emit_end_of_early_data_tls13(&mut st.transcript, cx.common);
1358
0
            cx.common.early_traffic = false;
1359
0
            cx.data.early_data.finished();
1360
0
            st.key_schedule
1361
0
                .set_handshake_encrypter(cx.common);
1362
0
        }
1363
1364
0
        let mut flight = HandshakeFlightTls13::new(&mut st.transcript);
1365
1366
        /* Send our authentication/finished messages.  These are still encrypted
1367
         * with our handshake keys. */
1368
0
        if let Some(client_auth) = st.client_auth {
1369
0
            match client_auth {
1370
                ClientAuthDetails::Empty {
1371
0
                    auth_context_tls13: auth_context,
1372
0
                } => {
1373
0
                    emit_certificate_tls13(&mut flight, None, auth_context);
1374
0
                }
1375
                ClientAuthDetails::Verify {
1376
0
                    auth_context_tls13: auth_context,
1377
                    ..
1378
0
                } if cx.data.ech_status == EchStatus::Rejected => {
1379
0
                    // If ECH was offered, and rejected, we MUST respond with
1380
0
                    // an empty certificate message.
1381
0
                    emit_certificate_tls13(&mut flight, None, auth_context);
1382
0
                }
1383
                ClientAuthDetails::Verify {
1384
0
                    certkey,
1385
0
                    signer,
1386
0
                    auth_context_tls13: auth_context,
1387
0
                    compressor,
1388
                } => {
1389
0
                    if let Some(compressor) = compressor {
1390
0
                        emit_compressed_certificate_tls13(
1391
0
                            &mut flight,
1392
0
                            &certkey,
1393
0
                            auth_context,
1394
0
                            compressor,
1395
0
                            &st.config,
1396
0
                        );
1397
0
                    } else {
1398
0
                        emit_certificate_tls13(&mut flight, Some(&certkey), auth_context);
1399
0
                    }
1400
0
                    emit_certverify_tls13(&mut flight, signer.as_ref())?;
1401
                }
1402
            }
1403
0
        }
1404
1405
0
        let (key_schedule_pre_finished, verify_data) = st
1406
0
            .key_schedule
1407
0
            .into_pre_finished_client_traffic(
1408
0
                hash_after_handshake,
1409
0
                flight.transcript.current_hash(),
1410
0
                &*st.config.key_log,
1411
0
                &st.randoms.client,
1412
0
            );
1413
1414
0
        emit_finished_tls13(&mut flight, &verify_data);
1415
0
        flight.finish(cx.common);
1416
1417
        /* We're now sure this server supports TLS1.3.  But if we run out of TLS1.3 tickets
1418
         * when connecting to it again, we definitely don't want to attempt a TLS1.2 resumption. */
1419
0
        st.config
1420
0
            .resumption
1421
0
            .store
1422
0
            .remove_tls12_session(&st.server_name);
1423
1424
        /* Now move to our application traffic keys. */
1425
0
        cx.common.check_aligned_handshake()?;
1426
0
        let (key_schedule, resumption) =
1427
0
            key_schedule_pre_finished.into_traffic(cx.common, st.transcript.current_hash());
1428
0
        cx.common
1429
0
            .start_traffic(&mut cx.sendable_plaintext);
1430
1431
        // Now that we've reached the end of the normal handshake we must enforce ECH acceptance by
1432
        // sending an alert and returning an error (potentially with retry configs) if the server
1433
        // did not accept our ECH offer.
1434
0
        if cx.data.ech_status == EchStatus::Rejected {
1435
0
            return Err(ech::fatal_alert_required(st.ech_retry_configs, cx.common));
1436
0
        }
1437
1438
0
        let st = ExpectTraffic {
1439
0
            config: st.config.clone(),
1440
0
            session_storage: st.config.resumption.store.clone(),
1441
0
            server_name: st.server_name,
1442
0
            suite: st.suite,
1443
0
            key_schedule,
1444
0
            resumption,
1445
0
            _cert_verified: st.cert_verified,
1446
0
            _sig_verified: st.sig_verified,
1447
0
            _fin_verified: fin,
1448
0
        };
1449
1450
0
        Ok(match cx.common.is_quic() {
1451
0
            true => Box::new(ExpectQuicTraffic(st)),
1452
0
            false => Box::new(st),
1453
        })
1454
0
    }
1455
1456
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1457
0
        self
1458
0
    }
1459
}
1460
1461
// -- Traffic transit state (TLS1.3) --
1462
// In this state we can be sent tickets, key updates,
1463
// and application data.
1464
struct ExpectTraffic {
1465
    config: Arc<ClientConfig>,
1466
    session_storage: Arc<dyn ClientSessionStore>,
1467
    server_name: ServerName<'static>,
1468
    suite: &'static Tls13CipherSuite,
1469
    key_schedule: KeyScheduleTraffic,
1470
    resumption: KeyScheduleResumption,
1471
    _cert_verified: verify::ServerCertVerified,
1472
    _sig_verified: verify::HandshakeSignatureValid,
1473
    _fin_verified: verify::FinishedMessageVerified,
1474
}
1475
1476
impl ExpectTraffic {
1477
0
    fn handle_new_ticket_impl(
1478
0
        &mut self,
1479
0
        cx: &mut KernelContext<'_>,
1480
0
        nst: &NewSessionTicketPayloadTls13,
1481
0
    ) -> Result<(), Error> {
1482
0
        let secret = self
1483
0
            .resumption
1484
0
            .derive_ticket_psk(&nst.nonce.0);
1485
1486
0
        let now = self.config.current_time()?;
1487
1488
        #[allow(unused_mut)]
1489
0
        let mut value = persist::Tls13ClientSessionValue::new(
1490
0
            self.suite,
1491
0
            nst.ticket.clone(),
1492
0
            secret.as_ref(),
1493
0
            cx.peer_certificates
1494
0
                .cloned()
1495
0
                .unwrap_or_default(),
1496
0
            &self.config.verifier,
1497
0
            &self.config.client_auth_cert_resolver,
1498
0
            now,
1499
0
            nst.lifetime,
1500
0
            nst.age_add,
1501
0
            nst.extensions
1502
0
                .max_early_data_size
1503
0
                .unwrap_or_default(),
1504
        );
1505
1506
0
        if cx.is_quic() {
1507
0
            if let Some(sz) = nst.extensions.max_early_data_size {
1508
0
                if sz != 0 && sz != 0xffff_ffff {
1509
0
                    return Err(PeerMisbehaved::InvalidMaxEarlyDataSize.into());
1510
0
                }
1511
0
            }
1512
1513
0
            if let Some(quic_params) = &cx.quic.params {
1514
0
                value.set_quic_params(quic_params);
1515
0
            }
1516
0
        }
1517
1518
0
        self.session_storage
1519
0
            .insert_tls13_ticket(self.server_name.clone(), value);
1520
0
        Ok(())
1521
0
    }
1522
1523
0
    fn handle_new_ticket_tls13(
1524
0
        &mut self,
1525
0
        cx: &mut ClientContext<'_>,
1526
0
        nst: &NewSessionTicketPayloadTls13,
1527
0
    ) -> Result<(), Error> {
1528
0
        let mut kcx = KernelContext {
1529
0
            peer_certificates: cx.common.peer_certificates.as_ref(),
1530
0
            protocol: cx.common.protocol,
1531
0
            quic: &cx.common.quic,
1532
0
        };
1533
0
        cx.common.tls13_tickets_received = cx
1534
0
            .common
1535
0
            .tls13_tickets_received
1536
0
            .saturating_add(1);
1537
0
        self.handle_new_ticket_impl(&mut kcx, nst)
1538
0
    }
1539
1540
0
    fn handle_key_update(
1541
0
        &mut self,
1542
0
        common: &mut CommonState,
1543
0
        key_update_request: &KeyUpdateRequest,
1544
0
    ) -> Result<(), Error> {
1545
0
        if let Protocol::Quic = common.protocol {
1546
0
            return Err(common.send_fatal_alert(
1547
0
                AlertDescription::UnexpectedMessage,
1548
0
                PeerMisbehaved::KeyUpdateReceivedInQuicConnection,
1549
0
            ));
1550
0
        }
1551
1552
        // Mustn't be interleaved with other handshake messages.
1553
0
        common.check_aligned_handshake()?;
1554
1555
0
        if common.should_update_key(key_update_request)? {
1556
0
            self.key_schedule
1557
0
                .update_encrypter_and_notify(common);
1558
0
        }
1559
1560
        // Update our read-side keys.
1561
0
        self.key_schedule
1562
0
            .update_decrypter(common);
1563
0
        Ok(())
1564
0
    }
1565
}
1566
1567
impl State<ClientConnectionData> for ExpectTraffic {
1568
0
    fn handle<'m>(
1569
0
        mut self: Box<Self>,
1570
0
        cx: &mut ClientContext<'_>,
1571
0
        m: Message<'m>,
1572
0
    ) -> hs::NextStateOrError<'m>
1573
0
    where
1574
0
        Self: 'm,
1575
    {
1576
0
        match m.payload {
1577
0
            MessagePayload::ApplicationData(payload) => cx
1578
0
                .common
1579
0
                .take_received_plaintext(payload),
1580
            MessagePayload::Handshake {
1581
0
                parsed: HandshakeMessagePayload(HandshakePayload::NewSessionTicketTls13(new_ticket)),
1582
                ..
1583
0
            } => self.handle_new_ticket_tls13(cx, &new_ticket)?,
1584
            MessagePayload::Handshake {
1585
0
                parsed: HandshakeMessagePayload(HandshakePayload::KeyUpdate(key_update)),
1586
                ..
1587
0
            } => self.handle_key_update(cx.common, &key_update)?,
1588
0
            payload => {
1589
0
                return Err(inappropriate_handshake_message(
1590
0
                    &payload,
1591
0
                    &[ContentType::ApplicationData, ContentType::Handshake],
1592
0
                    &[HandshakeType::NewSessionTicket, HandshakeType::KeyUpdate],
1593
0
                ));
1594
            }
1595
        }
1596
1597
0
        Ok(self)
1598
0
    }
1599
1600
0
    fn send_key_update_request(&mut self, common: &mut CommonState) -> Result<(), Error> {
1601
0
        self.key_schedule
1602
0
            .request_key_update_and_update_encrypter(common)
1603
0
    }
1604
1605
0
    fn export_keying_material(
1606
0
        &self,
1607
0
        output: &mut [u8],
1608
0
        label: &[u8],
1609
0
        context: Option<&[u8]>,
1610
0
    ) -> Result<(), Error> {
1611
0
        self.key_schedule
1612
0
            .export_keying_material(output, label, context)
1613
0
    }
1614
1615
0
    fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
1616
0
        self.key_schedule
1617
0
            .extract_secrets(Side::Client)
1618
0
    }
1619
1620
0
    fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
1621
0
        Ok(self)
1622
0
    }
1623
1624
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1625
0
        self
1626
0
    }
1627
}
1628
1629
impl KernelState for ExpectTraffic {
1630
0
    fn update_secrets(&mut self, dir: Direction) -> Result<ConnectionTrafficSecrets, Error> {
1631
0
        self.key_schedule
1632
0
            .refresh_traffic_secret(match dir {
1633
0
                Direction::Transmit => Side::Client,
1634
0
                Direction::Receive => Side::Server,
1635
            })
1636
0
    }
1637
1638
0
    fn handle_new_session_ticket(
1639
0
        &mut self,
1640
0
        cx: &mut KernelContext<'_>,
1641
0
        message: &NewSessionTicketPayloadTls13,
1642
0
    ) -> Result<(), Error> {
1643
0
        self.handle_new_ticket_impl(cx, message)
1644
0
    }
1645
}
1646
1647
struct ExpectQuicTraffic(ExpectTraffic);
1648
1649
impl State<ClientConnectionData> for ExpectQuicTraffic {
1650
0
    fn handle<'m>(
1651
0
        mut self: Box<Self>,
1652
0
        cx: &mut ClientContext<'_>,
1653
0
        m: Message<'m>,
1654
0
    ) -> hs::NextStateOrError<'m>
1655
0
    where
1656
0
        Self: 'm,
1657
    {
1658
0
        let nst = require_handshake_msg!(
1659
            m,
1660
            HandshakeType::NewSessionTicket,
1661
            HandshakePayload::NewSessionTicketTls13
1662
0
        )?;
1663
0
        self.0
1664
0
            .handle_new_ticket_tls13(cx, nst)?;
1665
0
        Ok(self)
1666
0
    }
1667
1668
0
    fn export_keying_material(
1669
0
        &self,
1670
0
        output: &mut [u8],
1671
0
        label: &[u8],
1672
0
        context: Option<&[u8]>,
1673
0
    ) -> Result<(), Error> {
1674
0
        self.0
1675
0
            .export_keying_material(output, label, context)
1676
0
    }
1677
1678
0
    fn into_external_state(self: Box<Self>) -> Result<Box<dyn KernelState + 'static>, Error> {
1679
0
        Ok(self)
1680
0
    }
1681
1682
0
    fn into_owned(self: Box<Self>) -> hs::NextState<'static> {
1683
0
        self
1684
0
    }
1685
}
1686
1687
impl KernelState for ExpectQuicTraffic {
1688
0
    fn update_secrets(&mut self, _: Direction) -> Result<ConnectionTrafficSecrets, Error> {
1689
0
        Err(Error::General(
1690
0
            "KeyUpdate is not supported for QUIC connections".into(),
1691
0
        ))
1692
0
    }
1693
1694
0
    fn handle_new_session_ticket(
1695
0
        &mut self,
1696
0
        cx: &mut KernelContext<'_>,
1697
0
        nst: &NewSessionTicketPayloadTls13,
1698
0
    ) -> Result<(), Error> {
1699
0
        self.0.handle_new_ticket_impl(cx, nst)
1700
0
    }
1701
}