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