1use alloc::boxed::Box;
2use alloc::vec::Vec;
3
4use pki_types::CertificateDer;
5
6use crate::crypto::SupportedKxGroup;
7use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion};
8use crate::error::{Error, InvalidMessage, PeerMisbehaved};
9use crate::hash_hs::HandshakeHash;
10use crate::log::{debug, error, warn};
11use crate::msgs::alert::AlertMessagePayload;
12use crate::msgs::base::Payload;
13use crate::msgs::codec::Codec;
14use crate::msgs::enums::{AlertLevel, KeyUpdateRequest};
15use crate::msgs::fragmenter::MessageFragmenter;
16use crate::msgs::handshake::{CertificateChain, HandshakeMessagePayload};
17use crate::msgs::message::{
18 Message, MessagePayload, OutboundChunks, OutboundOpaqueMessage, OutboundPlainMessage,
19 PlainMessage,
20};
21use crate::record_layer::PreEncryptAction;
22use crate::suites::{PartiallyExtractedSecrets, SupportedCipherSuite};
23#[cfg(feature = "tls12")]
24use crate::tls12::ConnectionSecrets;
25use crate::unbuffered::{EncryptError, InsufficientSizeError};
26use crate::vecbuf::ChunkVecBuffer;
27use crate::{quic, record_layer};
28
29/// Connection state common to both client and server connections.
30pub struct CommonState {
31 pub(crate) negotiated_version: Option<ProtocolVersion>,
32 pub(crate) handshake_kind: Option<HandshakeKind>,
33 pub(crate) side: Side,
34 pub(crate) record_layer: record_layer::RecordLayer,
35 pub(crate) suite: Option<SupportedCipherSuite>,
36 pub(crate) kx_state: KxState,
37 pub(crate) alpn_protocol: Option<Vec<u8>>,
38 pub(crate) aligned_handshake: bool,
39 pub(crate) may_send_application_data: bool,
40 pub(crate) may_receive_application_data: bool,
41 pub(crate) early_traffic: bool,
42 sent_fatal_alert: bool,
43 /// If we signaled end of stream.
44 pub(crate) has_sent_close_notify: bool,
45 /// If the peer has signaled end of stream.
46 pub(crate) has_received_close_notify: bool,
47 #[cfg(feature = "std")]
48 pub(crate) has_seen_eof: bool,
49 pub(crate) peer_certificates: Option<CertificateChain<'static>>,
50 message_fragmenter: MessageFragmenter,
51 pub(crate) received_plaintext: ChunkVecBuffer,
52 pub(crate) sendable_tls: ChunkVecBuffer,
53 queued_key_update_message: Option<Vec<u8>>,
54
55 /// Protocol whose key schedule should be used. Unused for TLS < 1.3.
56 pub(crate) protocol: Protocol,
57 pub(crate) quic: quic::Quic,
58 pub(crate) enable_secret_extraction: bool,
59 temper_counters: TemperCounters,
60 pub(crate) refresh_traffic_keys_pending: bool,
61 pub(crate) fips: bool,
62}
63
64impl CommonState {
65 pub(crate) fn new(side: Side) -> Self {
66 Self {
67 negotiated_version: None,
68 handshake_kind: None,
69 side,
70 record_layer: record_layer::RecordLayer::new(),
71 suite: None,
72 kx_state: KxState::default(),
73 alpn_protocol: None,
74 aligned_handshake: true,
75 may_send_application_data: false,
76 may_receive_application_data: false,
77 early_traffic: false,
78 sent_fatal_alert: false,
79 has_sent_close_notify: false,
80 has_received_close_notify: false,
81 #[cfg(feature = "std")]
82 has_seen_eof: false,
83 peer_certificates: None,
84 message_fragmenter: MessageFragmenter::default(),
85 received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
86 sendable_tls: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
87 queued_key_update_message: None,
88 protocol: Protocol::Tcp,
89 quic: quic::Quic::default(),
90 enable_secret_extraction: false,
91 temper_counters: TemperCounters::default(),
92 refresh_traffic_keys_pending: false,
93 fips: false,
94 }
95 }
96
97 /// Returns true if the caller should call [`Connection::write_tls`] as soon as possible.
98 ///
99 /// [`Connection::write_tls`]: crate::Connection::write_tls
100 pub fn wants_write(&self) -> bool {
101 !self.sendable_tls.is_empty()
102 }
103
104 /// Returns true if the connection is currently performing the TLS handshake.
105 ///
106 /// During this time plaintext written to the connection is buffered in memory. After
107 /// [`Connection::process_new_packets()`] has been called, this might start to return `false`
108 /// while the final handshake packets still need to be extracted from the connection's buffers.
109 ///
110 /// [`Connection::process_new_packets()`]: crate::Connection::process_new_packets
111 pub fn is_handshaking(&self) -> bool {
112 !(self.may_send_application_data && self.may_receive_application_data)
113 }
114
115 /// Retrieves the certificate chain or the raw public key used by the peer to authenticate.
116 ///
117 /// The order of the certificate chain is as it appears in the TLS
118 /// protocol: the first certificate relates to the peer, the
119 /// second certifies the first, the third certifies the second, and
120 /// so on.
121 ///
122 /// When using raw public keys, the first and only element is the raw public key.
123 ///
124 /// This is made available for both full and resumed handshakes.
125 ///
126 /// For clients, this is the certificate chain or the raw public key of the server.
127 ///
128 /// For servers, this is the certificate chain or the raw public key of the client,
129 /// if client authentication was completed.
130 ///
131 /// The return value is None until this value is available.
132 ///
133 /// Note: the return type of the 'certificate', when using raw public keys is `CertificateDer<'static>`
134 /// even though this should technically be a `SubjectPublicKeyInfoDer<'static>`.
135 /// This choice simplifies the API and ensures backwards compatibility.
136 pub fn peer_certificates(&self) -> Option<&[CertificateDer<'static>]> {
137 self.peer_certificates.as_deref()
138 }
139
140 /// Retrieves the protocol agreed with the peer via ALPN.
141 ///
142 /// A return value of `None` after handshake completion
143 /// means no protocol was agreed (because no protocols
144 /// were offered or accepted by the peer).
145 pub fn alpn_protocol(&self) -> Option<&[u8]> {
146 self.get_alpn_protocol()
147 }
148
149 /// Retrieves the ciphersuite agreed with the peer.
150 ///
151 /// This returns None until the ciphersuite is agreed.
152 pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
153 self.suite
154 }
155
156 /// Retrieves the key exchange group agreed with the peer.
157 ///
158 /// This function may return `None` depending on the state of the connection,
159 /// the type of handshake, and the protocol version.
160 ///
161 /// If [`CommonState::is_handshaking()`] is true this function will return `None`.
162 /// Similarly, if the [`CommonState::handshake_kind()`] is [`HandshakeKind::Resumed`]
163 /// and the [`CommonState::protocol_version()`] is TLS 1.2, then no key exchange will have
164 /// occurred and this function will return `None`.
165 pub fn negotiated_key_exchange_group(&self) -> Option<&'static dyn SupportedKxGroup> {
166 match self.kx_state {
167 KxState::Complete(group) => Some(group),
168 _ => None,
169 }
170 }
171
172 /// Retrieves the protocol version agreed with the peer.
173 ///
174 /// This returns `None` until the version is agreed.
175 pub fn protocol_version(&self) -> Option<ProtocolVersion> {
176 self.negotiated_version
177 }
178
179 /// Which kind of handshake was performed.
180 ///
181 /// This tells you whether the handshake was a resumption or not.
182 ///
183 /// This will return `None` before it is known which sort of
184 /// handshake occurred.
185 pub fn handshake_kind(&self) -> Option<HandshakeKind> {
186 self.handshake_kind
187 }
188
189 pub(crate) fn is_tls13(&self) -> bool {
190 matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
191 }
192
193 pub(crate) fn process_main_protocol<Data>(
194 &mut self,
195 msg: Message<'_>,
196 mut state: Box<dyn State<Data>>,
197 data: &mut Data,
198 sendable_plaintext: Option<&mut ChunkVecBuffer>,
199 ) -> Result<Box<dyn State<Data>>, Error> {
200 // For TLS1.2, outside of the handshake, send rejection alerts for
201 // renegotiation requests. These can occur any time.
202 if self.may_receive_application_data && !self.is_tls13() {
203 let reject_ty = match self.side {
204 Side::Client => HandshakeType::HelloRequest,
205 Side::Server => HandshakeType::ClientHello,
206 };
207 if msg.is_handshake_type(reject_ty) {
208 self.temper_counters
209 .received_renegotiation_request()?;
210 self.send_warning_alert(AlertDescription::NoRenegotiation);
211 return Ok(state);
212 }
213 }
214
215 let mut cx = Context {
216 common: self,
217 data,
218 sendable_plaintext,
219 };
220 match state.handle(&mut cx, msg) {
221 Ok(next) => {
222 state = next.into_owned();
223 Ok(state)
224 }
225 Err(e @ Error::InappropriateMessage { .. })
226 | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
227 Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
228 }
229 Err(e) => Err(e),
230 }
231 }
232
233 pub(crate) fn write_plaintext(
234 &mut self,
235 payload: OutboundChunks<'_>,
236 outgoing_tls: &mut [u8],
237 ) -> Result<usize, EncryptError> {
238 if payload.is_empty() {
239 return Ok(0);
240 }
241
242 let fragments = self
243 .message_fragmenter
244 .fragment_payload(
245 ContentType::ApplicationData,
246 ProtocolVersion::TLSv1_2,
247 payload.clone(),
248 );
249
250 for f in 0..fragments.len() {
251 match self
252 .record_layer
253 .pre_encrypt_action(f as u64)
254 {
255 PreEncryptAction::Nothing => {}
256 PreEncryptAction::RefreshOrClose => match self.negotiated_version {
257 Some(ProtocolVersion::TLSv1_3) => {
258 // driven by caller, as we don't have the `State` here
259 self.refresh_traffic_keys_pending = true;
260 }
261 _ => {
262 error!(
263 "traffic keys exhausted, closing connection to prevent security failure"
264 );
265 self.send_close_notify();
266 return Err(EncryptError::EncryptExhausted);
267 }
268 },
269 PreEncryptAction::Refuse => {
270 return Err(EncryptError::EncryptExhausted);
271 }
272 }
273 }
274
275 self.perhaps_write_key_update();
276
277 self.check_required_size(outgoing_tls, fragments)?;
278
279 let fragments = self
280 .message_fragmenter
281 .fragment_payload(
282 ContentType::ApplicationData,
283 ProtocolVersion::TLSv1_2,
284 payload,
285 );
286
287 Ok(self.write_fragments(outgoing_tls, fragments))
288 }
289
290 // Changing the keys must not span any fragmented handshake
291 // messages. Otherwise the defragmented messages will have
292 // been protected with two different record layer protections,
293 // which is illegal. Not mentioned in RFC.
294 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
295 if !self.aligned_handshake {
296 Err(self.send_fatal_alert(
297 AlertDescription::UnexpectedMessage,
298 PeerMisbehaved::KeyEpochWithPendingFragment,
299 ))
300 } else {
301 Ok(())
302 }
303 }
304
305 /// Fragment `m`, encrypt the fragments, and then queue
306 /// the encrypted fragments for sending.
307 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
308 let iter = self
309 .message_fragmenter
310 .fragment_message(&m);
311 for m in iter {
312 self.send_single_fragment(m);
313 }
314 }
315
316 /// Like send_msg_encrypt, but operate on an appdata directly.
317 fn send_appdata_encrypt(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
318 // Here, the limit on sendable_tls applies to encrypted data,
319 // but we're respecting it for plaintext data -- so we'll
320 // be out by whatever the cipher+record overhead is. That's a
321 // constant and predictable amount, so it's not a terrible issue.
322 let len = match limit {
323 #[cfg(feature = "std")]
324 Limit::Yes => self
325 .sendable_tls
326 .apply_limit(payload.len()),
327 Limit::No => payload.len(),
328 };
329
330 let iter = self
331 .message_fragmenter
332 .fragment_payload(
333 ContentType::ApplicationData,
334 ProtocolVersion::TLSv1_2,
335 payload.split_at(len).0,
336 );
337 for m in iter {
338 self.send_single_fragment(m);
339 }
340
341 len
342 }
343
344 fn send_single_fragment(&mut self, m: OutboundPlainMessage<'_>) {
345 if m.typ == ContentType::Alert {
346 // Alerts are always sendable -- never quashed by a PreEncryptAction.
347 let em = self.record_layer.encrypt_outgoing(m);
348 self.queue_tls_message(em);
349 return;
350 }
351
352 match self
353 .record_layer
354 .next_pre_encrypt_action()
355 {
356 PreEncryptAction::Nothing => {}
357
358 // Close connection once we start to run out of
359 // sequence space.
360 PreEncryptAction::RefreshOrClose => {
361 match self.negotiated_version {
362 Some(ProtocolVersion::TLSv1_3) => {
363 // driven by caller, as we don't have the `State` here
364 self.refresh_traffic_keys_pending = true;
365 }
366 _ => {
367 error!(
368 "traffic keys exhausted, closing connection to prevent security failure"
369 );
370 self.send_close_notify();
371 return;
372 }
373 }
374 }
375
376 // Refuse to wrap counter at all costs. This
377 // is basically untestable unfortunately.
378 PreEncryptAction::Refuse => {
379 return;
380 }
381 };
382
383 let em = self.record_layer.encrypt_outgoing(m);
384 self.queue_tls_message(em);
385 }
386
387 fn send_plain_non_buffering(&mut self, payload: OutboundChunks<'_>, limit: Limit) -> usize {
388 debug_assert!(self.may_send_application_data);
389 debug_assert!(self.record_layer.is_encrypting());
390
391 if payload.is_empty() {
392 // Don't send empty fragments.
393 return 0;
394 }
395
396 self.send_appdata_encrypt(payload, limit)
397 }
398
399 /// Mark the connection as ready to send application data.
400 ///
401 /// Also flush `sendable_plaintext` if it is `Some`.
402 pub(crate) fn start_outgoing_traffic(
403 &mut self,
404 sendable_plaintext: &mut Option<&mut ChunkVecBuffer>,
405 ) {
406 self.may_send_application_data = true;
407 if let Some(sendable_plaintext) = sendable_plaintext {
408 self.flush_plaintext(sendable_plaintext);
409 }
410 }
411
412 /// Mark the connection as ready to send and receive application data.
413 ///
414 /// Also flush `sendable_plaintext` if it is `Some`.
415 pub(crate) fn start_traffic(&mut self, sendable_plaintext: &mut Option<&mut ChunkVecBuffer>) {
416 self.may_receive_application_data = true;
417 self.start_outgoing_traffic(sendable_plaintext);
418 }
419
420 /// Send any buffered plaintext. Plaintext is buffered if
421 /// written during handshake.
422 fn flush_plaintext(&mut self, sendable_plaintext: &mut ChunkVecBuffer) {
423 if !self.may_send_application_data {
424 return;
425 }
426
427 while let Some(buf) = sendable_plaintext.pop() {
428 self.send_plain_non_buffering(buf.as_slice().into(), Limit::No);
429 }
430 }
431
432 // Put m into sendable_tls for writing.
433 fn queue_tls_message(&mut self, m: OutboundOpaqueMessage) {
434 self.perhaps_write_key_update();
435 self.sendable_tls.append(m.encode());
436 }
437
438 pub(crate) fn perhaps_write_key_update(&mut self) {
439 if let Some(message) = self.queued_key_update_message.take() {
440 self.sendable_tls.append(message);
441 }
442 }
443
444 /// Send a raw TLS message, fragmenting it if needed.
445 pub(crate) fn send_msg(&mut self, m: Message<'_>, must_encrypt: bool) {
446 {
447 if let Protocol::Quic = self.protocol {
448 if let MessagePayload::Alert(alert) = m.payload {
449 self.quic.alert = Some(alert.description);
450 } else {
451 debug_assert!(
452 matches!(
453 m.payload,
454 MessagePayload::Handshake { .. } | MessagePayload::HandshakeFlight(_)
455 ),
456 "QUIC uses TLS for the cryptographic handshake only"
457 );
458 let mut bytes = Vec::new();
459 m.payload.encode(&mut bytes);
460 self.quic
461 .hs_queue
462 .push_back((must_encrypt, bytes));
463 }
464 return;
465 }
466 }
467 if !must_encrypt {
468 let msg = &m.into();
469 let iter = self
470 .message_fragmenter
471 .fragment_message(msg);
472 for m in iter {
473 self.queue_tls_message(m.to_unencrypted_opaque());
474 }
475 } else {
476 self.send_msg_encrypt(m.into());
477 }
478 }
479
480 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload<'_>) {
481 self.received_plaintext
482 .append(bytes.into_vec());
483 }
484
485 #[cfg(feature = "tls12")]
486 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
487 let (dec, enc) = secrets.make_cipher_pair(side);
488 self.record_layer
489 .prepare_message_encrypter(
490 enc,
491 secrets
492 .suite()
493 .common
494 .confidentiality_limit,
495 );
496 self.record_layer
497 .prepare_message_decrypter(dec);
498 }
499
500 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
501 self.send_fatal_alert(AlertDescription::MissingExtension, why)
502 }
503
504 fn send_warning_alert(&mut self, desc: AlertDescription) {
505 warn!("Sending warning alert {:?}", desc);
506 self.send_warning_alert_no_log(desc);
507 }
508
509 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
510 // Reject unknown AlertLevels.
511 if let AlertLevel::Unknown(_) = alert.level {
512 return Err(self.send_fatal_alert(
513 AlertDescription::IllegalParameter,
514 Error::AlertReceived(alert.description),
515 ));
516 }
517
518 // If we get a CloseNotify, make a note to declare EOF to our
519 // caller. But do not treat unauthenticated alerts like this.
520 if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
521 self.has_received_close_notify = true;
522 return Ok(());
523 }
524
525 // Warnings are nonfatal for TLS1.2, but outlawed in TLS1.3
526 // (except, for no good reason, user_cancelled).
527 let err = Error::AlertReceived(alert.description);
528 if alert.level == AlertLevel::Warning {
529 self.temper_counters
530 .received_warning_alert()?;
531 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
532 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
533 }
534
535 // Some implementations send pointless `user_canceled` alerts, don't log them
536 // in release mode (https://bugs.openjdk.org/browse/JDK-8323517).
537 if alert.description != AlertDescription::UserCanceled || cfg!(debug_assertions) {
538 warn!("TLS alert warning received: {alert:?}");
539 }
540
541 return Ok(());
542 }
543
544 Err(err)
545 }
546
547 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
548 self.send_fatal_alert(
549 match &err {
550 Error::InvalidCertificate(e) => e.clone().into(),
551 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
552 _ => AlertDescription::HandshakeFailure,
553 },
554 err,
555 )
556 }
557
558 pub(crate) fn send_fatal_alert(
559 &mut self,
560 desc: AlertDescription,
561 err: impl Into<Error>,
562 ) -> Error {
563 debug_assert!(!self.sent_fatal_alert);
564 let m = Message::build_alert(AlertLevel::Fatal, desc);
565 self.send_msg(m, self.record_layer.is_encrypting());
566 self.sent_fatal_alert = true;
567 err.into()
568 }
569
570 /// Queues a `close_notify` warning alert to be sent in the next
571 /// [`Connection::write_tls`] call. This informs the peer that the
572 /// connection is being closed.
573 ///
574 /// Does nothing if any `close_notify` or fatal alert was already sent.
575 ///
576 /// [`Connection::write_tls`]: crate::Connection::write_tls
577 pub fn send_close_notify(&mut self) {
578 if self.sent_fatal_alert {
579 return;
580 }
581 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
582 self.sent_fatal_alert = true;
583 self.has_sent_close_notify = true;
584 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
585 }
586
587 pub(crate) fn eager_send_close_notify(
588 &mut self,
589 outgoing_tls: &mut [u8],
590 ) -> Result<usize, EncryptError> {
591 self.send_close_notify();
592 self.check_required_size(outgoing_tls, [].into_iter())?;
593 Ok(self.write_fragments(outgoing_tls, [].into_iter()))
594 }
595
596 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
597 let m = Message::build_alert(AlertLevel::Warning, desc);
598 self.send_msg(m, self.record_layer.is_encrypting());
599 }
600
601 fn check_required_size<'a>(
602 &self,
603 outgoing_tls: &mut [u8],
604 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
605 ) -> Result<(), EncryptError> {
606 let mut required_size = self.sendable_tls.len();
607
608 for m in fragments {
609 required_size += m.encoded_len(&self.record_layer);
610 }
611
612 if required_size > outgoing_tls.len() {
613 return Err(EncryptError::InsufficientSize(InsufficientSizeError {
614 required_size,
615 }));
616 }
617
618 Ok(())
619 }
620
621 fn write_fragments<'a>(
622 &mut self,
623 outgoing_tls: &mut [u8],
624 fragments: impl Iterator<Item = OutboundPlainMessage<'a>>,
625 ) -> usize {
626 let mut written = 0;
627
628 // Any pre-existing encrypted messages in `sendable_tls` must
629 // be output before encrypting any of the `fragments`.
630 while let Some(message) = self.sendable_tls.pop() {
631 let len = message.len();
632 outgoing_tls[written..written + len].copy_from_slice(&message);
633 written += len;
634 }
635
636 for m in fragments {
637 let em = self
638 .record_layer
639 .encrypt_outgoing(m)
640 .encode();
641
642 let len = em.len();
643 outgoing_tls[written..written + len].copy_from_slice(&em);
644 written += len;
645 }
646
647 written
648 }
649
650 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
651 self.message_fragmenter
652 .set_max_fragment_size(new)
653 }
654
655 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
656 self.alpn_protocol
657 .as_ref()
658 .map(AsRef::as_ref)
659 }
660
661 /// Returns true if the caller should call [`Connection::read_tls`] as soon
662 /// as possible.
663 ///
664 /// If there is pending plaintext data to read with [`Connection::reader`],
665 /// this returns false. If your application respects this mechanism,
666 /// only one full TLS message will be buffered by rustls.
667 ///
668 /// [`Connection::reader`]: crate::Connection::reader
669 /// [`Connection::read_tls`]: crate::Connection::read_tls
670 pub fn wants_read(&self) -> bool {
671 // We want to read more data all the time, except when we have unprocessed plaintext.
672 // This provides back-pressure to the TCP buffers. We also don't want to read more after
673 // the peer has sent us a close notification.
674 //
675 // In the handshake case we don't have readable plaintext before the handshake has
676 // completed, but also don't want to read if we still have sendable tls.
677 self.received_plaintext.is_empty()
678 && !self.has_received_close_notify
679 && (self.may_send_application_data || self.sendable_tls.is_empty())
680 }
681
682 pub(crate) fn current_io_state(&self) -> IoState {
683 IoState {
684 tls_bytes_to_write: self.sendable_tls.len(),
685 plaintext_bytes_to_read: self.received_plaintext.len(),
686 peer_has_closed: self.has_received_close_notify,
687 }
688 }
689
690 pub(crate) fn is_quic(&self) -> bool {
691 self.protocol == Protocol::Quic
692 }
693
694 pub(crate) fn should_update_key(
695 &mut self,
696 key_update_request: &KeyUpdateRequest,
697 ) -> Result<bool, Error> {
698 self.temper_counters
699 .received_key_update_request()?;
700
701 match key_update_request {
702 KeyUpdateRequest::UpdateNotRequested => Ok(false),
703 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
704 _ => Err(self.send_fatal_alert(
705 AlertDescription::IllegalParameter,
706 InvalidMessage::InvalidKeyUpdate,
707 )),
708 }
709 }
710
711 pub(crate) fn enqueue_key_update_notification(&mut self) {
712 let message = PlainMessage::from(Message::build_key_update_notify());
713 self.queued_key_update_message = Some(
714 self.record_layer
715 .encrypt_outgoing(message.borrow_outbound())
716 .encode(),
717 );
718 }
719
720 pub(crate) fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
721 self.temper_counters
722 .received_tls13_change_cipher_spec()
723 }
724}
725
726#[cfg(feature = "std")]
727impl CommonState {
728 /// Send plaintext application data, fragmenting and
729 /// encrypting it as it goes out.
730 ///
731 /// If internal buffers are too small, this function will not accept
732 /// all the data.
733 pub(crate) fn buffer_plaintext(
734 &mut self,
735 payload: OutboundChunks<'_>,
736 sendable_plaintext: &mut ChunkVecBuffer,
737 ) -> usize {
738 self.perhaps_write_key_update();
739 self.send_plain(payload, Limit::Yes, sendable_plaintext)
740 }
741
742 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
743 debug_assert!(self.early_traffic);
744 debug_assert!(self.record_layer.is_encrypting());
745
746 if data.is_empty() {
747 // Don't send empty fragments.
748 return 0;
749 }
750
751 self.send_appdata_encrypt(data.into(), Limit::Yes)
752 }
753
754 /// Encrypt and send some plaintext `data`. `limit` controls
755 /// whether the per-connection buffer limits apply.
756 ///
757 /// Returns the number of bytes written from `data`: this might
758 /// be less than `data.len()` if buffer limits were exceeded.
759 fn send_plain(
760 &mut self,
761 payload: OutboundChunks<'_>,
762 limit: Limit,
763 sendable_plaintext: &mut ChunkVecBuffer,
764 ) -> usize {
765 if !self.may_send_application_data {
766 // If we haven't completed handshaking, buffer
767 // plaintext to send once we do.
768 let len = match limit {
769 Limit::Yes => sendable_plaintext.append_limited_copy(payload),
770 Limit::No => sendable_plaintext.append(payload.to_vec()),
771 };
772 return len;
773 }
774
775 self.send_plain_non_buffering(payload, limit)
776 }
777}
778
779/// Describes which sort of handshake happened.
780#[derive(Debug, PartialEq, Clone, Copy)]
781pub enum HandshakeKind {
782 /// A full handshake.
783 ///
784 /// This is the typical TLS connection initiation process when resumption is
785 /// not yet unavailable, and the initial `ClientHello` was accepted by the server.
786 Full,
787
788 /// A full TLS1.3 handshake, with an extra round-trip for a `HelloRetryRequest`.
789 ///
790 /// The server can respond with a `HelloRetryRequest` if the initial `ClientHello`
791 /// is unacceptable for several reasons, the most likely if no supported key
792 /// shares were offered by the client.
793 FullWithHelloRetryRequest,
794
795 /// A resumed handshake.
796 ///
797 /// Resumed handshakes involve fewer round trips and less cryptography than
798 /// full ones, but can only happen when the peers have previously done a full
799 /// handshake together, and then remember data about it.
800 Resumed,
801}
802
803/// Values of this structure are returned from [`Connection::process_new_packets`]
804/// and tell the caller the current I/O state of the TLS connection.
805///
806/// [`Connection::process_new_packets`]: crate::Connection::process_new_packets
807#[derive(Debug, Eq, PartialEq)]
808pub struct IoState {
809 tls_bytes_to_write: usize,
810 plaintext_bytes_to_read: usize,
811 peer_has_closed: bool,
812}
813
814impl IoState {
815 /// How many bytes could be written by [`Connection::write_tls`] if called
816 /// right now. A non-zero value implies [`CommonState::wants_write`].
817 ///
818 /// [`Connection::write_tls`]: crate::Connection::write_tls
819 pub fn tls_bytes_to_write(&self) -> usize {
820 self.tls_bytes_to_write
821 }
822
823 /// How many plaintext bytes could be obtained via [`std::io::Read`]
824 /// without further I/O.
825 pub fn plaintext_bytes_to_read(&self) -> usize {
826 self.plaintext_bytes_to_read
827 }
828
829 /// True if the peer has sent us a close_notify alert. This is
830 /// the TLS mechanism to securely half-close a TLS connection,
831 /// and signifies that the peer will not send any further data
832 /// on this connection.
833 ///
834 /// This is also signalled via returning `Ok(0)` from
835 /// [`std::io::Read`], after all the received bytes have been
836 /// retrieved.
837 pub fn peer_has_closed(&self) -> bool {
838 self.peer_has_closed
839 }
840}
841
842pub(crate) trait State<Data>: Send + Sync {
843 fn handle<'m>(
844 self: Box<Self>,
845 cx: &mut Context<'_, Data>,
846 message: Message<'m>,
847 ) -> Result<Box<dyn State<Data> + 'm>, Error>
848 where
849 Self: 'm;
850
851 fn export_keying_material(
852 &self,
853 _output: &mut [u8],
854 _label: &[u8],
855 _context: Option<&[u8]>,
856 ) -> Result<(), Error> {
857 Err(Error::HandshakeNotComplete)
858 }
859
860 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
861 Err(Error::HandshakeNotComplete)
862 }
863
864 fn send_key_update_request(&mut self, _common: &mut CommonState) -> Result<(), Error> {
865 Err(Error::HandshakeNotComplete)
866 }
867
868 fn handle_decrypt_error(&self) {}
869
870 fn into_owned(self: Box<Self>) -> Box<dyn State<Data> + 'static>;
871}
872
873pub(crate) struct Context<'a, Data> {
874 pub(crate) common: &'a mut CommonState,
875 pub(crate) data: &'a mut Data,
876 /// Buffered plaintext. This is `Some` if any plaintext was written during handshake and `None`
877 /// otherwise.
878 pub(crate) sendable_plaintext: Option<&'a mut ChunkVecBuffer>,
879}
880
881/// Side of the connection.
882#[derive(Clone, Copy, Debug, PartialEq)]
883pub enum Side {
884 /// A client initiates the connection.
885 Client,
886 /// A server waits for a client to connect.
887 Server,
888}
889
890impl Side {
891 pub(crate) fn peer(&self) -> Self {
892 match self {
893 Self::Client => Self::Server,
894 Self::Server => Self::Client,
895 }
896 }
897}
898
899#[derive(Copy, Clone, Eq, PartialEq, Debug)]
900pub(crate) enum Protocol {
901 Tcp,
902 Quic,
903}
904
905enum Limit {
906 #[cfg(feature = "std")]
907 Yes,
908 No,
909}
910
911/// Tracking technically-allowed protocol actions
912/// that we limit to avoid denial-of-service vectors.
913struct TemperCounters {
914 allowed_warning_alerts: u8,
915 allowed_renegotiation_requests: u8,
916 allowed_key_update_requests: u8,
917 allowed_middlebox_ccs: u8,
918}
919
920impl TemperCounters {
921 fn received_warning_alert(&mut self) -> Result<(), Error> {
922 match self.allowed_warning_alerts {
923 0 => Err(PeerMisbehaved::TooManyWarningAlertsReceived.into()),
924 _ => {
925 self.allowed_warning_alerts -= 1;
926 Ok(())
927 }
928 }
929 }
930
931 fn received_renegotiation_request(&mut self) -> Result<(), Error> {
932 match self.allowed_renegotiation_requests {
933 0 => Err(PeerMisbehaved::TooManyRenegotiationRequests.into()),
934 _ => {
935 self.allowed_renegotiation_requests -= 1;
936 Ok(())
937 }
938 }
939 }
940
941 fn received_key_update_request(&mut self) -> Result<(), Error> {
942 match self.allowed_key_update_requests {
943 0 => Err(PeerMisbehaved::TooManyKeyUpdateRequests.into()),
944 _ => {
945 self.allowed_key_update_requests -= 1;
946 Ok(())
947 }
948 }
949 }
950
951 fn received_tls13_change_cipher_spec(&mut self) -> Result<(), Error> {
952 match self.allowed_middlebox_ccs {
953 0 => Err(PeerMisbehaved::IllegalMiddleboxChangeCipherSpec.into()),
954 _ => {
955 self.allowed_middlebox_ccs -= 1;
956 Ok(())
957 }
958 }
959 }
960}
961
962impl Default for TemperCounters {
963 fn default() -> Self {
964 Self {
965 // cf. BoringSSL `kMaxWarningAlerts`
966 // <https://github.com/google/boringssl/blob/dec5989b793c56ad4dd32173bd2d8595ca78b398/ssl/tls_record.cc#L137-L139>
967 allowed_warning_alerts: 4,
968
969 // we rebuff renegotiation requests with a `NoRenegotiation` warning alerts.
970 // a second request after this is fatal.
971 allowed_renegotiation_requests: 1,
972
973 // cf. BoringSSL `kMaxKeyUpdates`
974 // <https://github.com/google/boringssl/blob/dec5989b793c56ad4dd32173bd2d8595ca78b398/ssl/tls13_both.cc#L35-L38>
975 allowed_key_update_requests: 32,
976
977 // At most two CCS are allowed: one after each ClientHello (recall a second
978 // ClientHello happens after a HelloRetryRequest).
979 //
980 // note BoringSSL allows up to 32.
981 allowed_middlebox_ccs: 2,
982 }
983 }
984}
985
986#[derive(Debug, Default)]
987pub(crate) enum KxState {
988 #[default]
989 None,
990 Start(&'static dyn SupportedKxGroup),
991 Complete(&'static dyn SupportedKxGroup),
992}
993
994impl KxState {
995 pub(crate) fn complete(&mut self) {
996 debug_assert!(matches!(self, Self::Start(_)));
997 if let Self::Start(group: &mut &'static (dyn SupportedKxGroup + 'static)) = self {
998 *self = Self::Complete(*group);
999 }
1000 }
1001}
1002
1003pub(crate) struct HandshakeFlight<'a, const TLS13: bool> {
1004 pub(crate) transcript: &'a mut HandshakeHash,
1005 body: Vec<u8>,
1006}
1007
1008impl<'a, const TLS13: bool> HandshakeFlight<'a, TLS13> {
1009 pub(crate) fn new(transcript: &'a mut HandshakeHash) -> Self {
1010 Self {
1011 transcript,
1012 body: Vec::new(),
1013 }
1014 }
1015
1016 pub(crate) fn add(&mut self, hs: HandshakeMessagePayload<'_>) {
1017 let start_len = self.body.len();
1018 hs.encode(&mut self.body);
1019 self.transcript
1020 .add(&self.body[start_len..]);
1021 }
1022
1023 pub(crate) fn finish(self, common: &mut CommonState) {
1024 common.send_msg(
1025 Message {
1026 version: match TLS13 {
1027 true => ProtocolVersion::TLSv1_3,
1028 false => ProtocolVersion::TLSv1_2,
1029 },
1030 payload: MessagePayload::HandshakeFlight(Payload::new(self.body)),
1031 },
1032 TLS13,
1033 );
1034 }
1035}
1036
1037#[cfg(feature = "tls12")]
1038pub(crate) type HandshakeFlightTls12<'a> = HandshakeFlight<'a, false>;
1039pub(crate) type HandshakeFlightTls13<'a> = HandshakeFlight<'a, true>;
1040
1041const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
1042pub(crate) const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;
1043