1use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion};
2use crate::error::{Error, InvalidMessage, PeerMisbehaved};
3use crate::key;
4#[cfg(feature = "logging")]
5use crate::log::{debug, warn};
6use crate::msgs::alert::AlertMessagePayload;
7use crate::msgs::base::Payload;
8use crate::msgs::enums::{AlertLevel, KeyUpdateRequest};
9use crate::msgs::fragmenter::MessageFragmenter;
10#[cfg(feature = "quic")]
11use crate::msgs::message::MessagePayload;
12use crate::msgs::message::{BorrowedPlainMessage, Message, OpaqueMessage, PlainMessage};
13#[cfg(feature = "quic")]
14use crate::quic;
15use crate::record_layer;
16#[cfg(feature = "secret_extraction")]
17use crate::suites::PartiallyExtractedSecrets;
18use crate::suites::SupportedCipherSuite;
19#[cfg(feature = "tls12")]
20use crate::tls12::ConnectionSecrets;
21use crate::vecbuf::ChunkVecBuffer;
22
23pub struct CommonState {
25 pub(crate) negotiated_version: Option<ProtocolVersion>,
26 pub(crate) side: Side,
27 pub(crate) record_layer: record_layer::RecordLayer,
28 pub(crate) suite: Option<SupportedCipherSuite>,
29 pub(crate) alpn_protocol: Option<Vec<u8>>,
30 pub(crate) aligned_handshake: bool,
31 pub(crate) may_send_application_data: bool,
32 pub(crate) may_receive_application_data: bool,
33 pub(crate) early_traffic: bool,
34 sent_fatal_alert: bool,
35 pub(crate) has_received_close_notify: bool,
37 pub(crate) has_seen_eof: bool,
38 pub(crate) received_middlebox_ccs: u8,
39 pub(crate) peer_certificates: Option<Vec<key::Certificate>>,
40 message_fragmenter: MessageFragmenter,
41 pub(crate) received_plaintext: ChunkVecBuffer,
42 sendable_plaintext: ChunkVecBuffer,
43 pub(crate) sendable_tls: ChunkVecBuffer,
44 queued_key_update_message: Option<Vec<u8>>,
45
46 #[allow(dead_code)] pub(crate) protocol: Protocol,
49 #[cfg(feature = "quic")]
50 pub(crate) quic: quic::Quic,
51 #[cfg(feature = "secret_extraction")]
52 pub(crate) enable_secret_extraction: bool,
53}
54
55impl CommonState {
56 pub(crate) fn new(side: Side) -> Self {
57 Self {
58 negotiated_version: None,
59 side,
60 record_layer: record_layer::RecordLayer::new(),
61 suite: None,
62 alpn_protocol: None,
63 aligned_handshake: true,
64 may_send_application_data: false,
65 may_receive_application_data: false,
66 early_traffic: false,
67 sent_fatal_alert: false,
68 has_received_close_notify: false,
69 has_seen_eof: false,
70 received_middlebox_ccs: 0,
71 peer_certificates: None,
72 message_fragmenter: MessageFragmenter::default(),
73 received_plaintext: ChunkVecBuffer::new(Some(DEFAULT_RECEIVED_PLAINTEXT_LIMIT)),
74 sendable_plaintext: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
75 sendable_tls: ChunkVecBuffer::new(Some(DEFAULT_BUFFER_LIMIT)),
76 queued_key_update_message: None,
77
78 protocol: Protocol::Tcp,
79 #[cfg(feature = "quic")]
80 quic: quic::Quic::default(),
81 #[cfg(feature = "secret_extraction")]
82 enable_secret_extraction: false,
83 }
84 }
85
86 pub fn wants_write(&self) -> bool {
90 !self.sendable_tls.is_empty()
91 }
92
93 pub fn is_handshaking(&self) -> bool {
101 !(self.may_send_application_data && self.may_receive_application_data)
102 }
103
104 pub fn peer_certificates(&self) -> Option<&[key::Certificate]> {
120 self.peer_certificates.as_deref()
121 }
122
123 pub fn alpn_protocol(&self) -> Option<&[u8]> {
129 self.get_alpn_protocol()
130 }
131
132 pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
136 self.suite
137 }
138
139 pub fn protocol_version(&self) -> Option<ProtocolVersion> {
143 self.negotiated_version
144 }
145
146 pub(crate) fn is_tls13(&self) -> bool {
147 matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
148 }
149
150 pub(crate) fn process_main_protocol<Data>(
151 &mut self,
152 msg: Message,
153 mut state: Box<dyn State<Data>>,
154 data: &mut Data,
155 ) -> Result<Box<dyn State<Data>>, Error> {
156 if self.may_receive_application_data && !self.is_tls13() {
159 let reject_ty = match self.side {
160 Side::Client => HandshakeType::HelloRequest,
161 Side::Server => HandshakeType::ClientHello,
162 };
163 if msg.is_handshake_type(reject_ty) {
164 self.send_warning_alert(AlertDescription::NoRenegotiation);
165 return Ok(state);
166 }
167 }
168
169 let mut cx = Context { common: self, data };
170 match state.handle(&mut cx, msg) {
171 Ok(next) => {
172 state = next;
173 Ok(state)
174 }
175 Err(e @ Error::InappropriateMessage { .. })
176 | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
177 Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
178 }
179 Err(e) => Err(e),
180 }
181 }
182
183 pub(crate) fn send_some_plaintext(&mut self, data: &[u8]) -> usize {
189 self.perhaps_write_key_update();
190 self.send_plain(data, Limit::Yes)
191 }
192
193 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
194 debug_assert!(self.early_traffic);
195 debug_assert!(self.record_layer.is_encrypting());
196
197 if data.is_empty() {
198 return 0;
200 }
201
202 self.send_appdata_encrypt(data, Limit::Yes)
203 }
204
205 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
210 if !self.aligned_handshake {
211 Err(self.send_fatal_alert(
212 AlertDescription::UnexpectedMessage,
213 PeerMisbehaved::KeyEpochWithPendingFragment,
214 ))
215 } else {
216 Ok(())
217 }
218 }
219
220 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
223 let iter = self
224 .message_fragmenter
225 .fragment_message(&m);
226 for m in iter {
227 self.send_single_fragment(m);
228 }
229 }
230
231 fn send_appdata_encrypt(&mut self, payload: &[u8], limit: Limit) -> usize {
233 let len = match limit {
238 Limit::Yes => self
239 .sendable_tls
240 .apply_limit(payload.len()),
241 Limit::No => payload.len(),
242 };
243
244 let iter = self.message_fragmenter.fragment_slice(
245 ContentType::ApplicationData,
246 ProtocolVersion::TLSv1_2,
247 &payload[..len],
248 );
249 for m in iter {
250 self.send_single_fragment(m);
251 }
252
253 len
254 }
255
256 fn send_single_fragment(&mut self, m: BorrowedPlainMessage) {
257 if self
260 .record_layer
261 .wants_close_before_encrypt()
262 {
263 self.send_close_notify();
264 }
265
266 if self.record_layer.encrypt_exhausted() {
269 return;
270 }
271
272 let em = self.record_layer.encrypt_outgoing(m);
273 self.queue_tls_message(em);
274 }
275
276 fn send_plain(&mut self, data: &[u8], limit: Limit) -> usize {
282 if !self.may_send_application_data {
283 let len = match limit {
286 Limit::Yes => self
287 .sendable_plaintext
288 .append_limited_copy(data),
289 Limit::No => self
290 .sendable_plaintext
291 .append(data.to_vec()),
292 };
293 return len;
294 }
295
296 debug_assert!(self.record_layer.is_encrypting());
297
298 if data.is_empty() {
299 return 0;
301 }
302
303 self.send_appdata_encrypt(data, limit)
304 }
305
306 pub(crate) fn start_outgoing_traffic(&mut self) {
307 self.may_send_application_data = true;
308 self.flush_plaintext();
309 }
310
311 pub(crate) fn start_traffic(&mut self) {
312 self.may_receive_application_data = true;
313 self.start_outgoing_traffic();
314 }
315
316 pub fn set_buffer_limit(&mut self, limit: Option<usize>) {
360 self.sendable_plaintext.set_limit(limit);
361 self.sendable_tls.set_limit(limit);
362 }
363
364 fn flush_plaintext(&mut self) {
367 if !self.may_send_application_data {
368 return;
369 }
370
371 while let Some(buf) = self.sendable_plaintext.pop() {
372 self.send_plain(&buf, Limit::No);
373 }
374 }
375
376 fn queue_tls_message(&mut self, m: OpaqueMessage) {
378 self.sendable_tls.append(m.encode());
379 }
380
381 pub(crate) fn send_msg(&mut self, m: Message, must_encrypt: bool) {
383 #[cfg(feature = "quic")]
384 {
385 if let Protocol::Quic = self.protocol {
386 if let MessagePayload::Alert(alert) = m.payload {
387 self.quic.alert = Some(alert.description);
388 } else {
389 debug_assert!(
390 matches!(m.payload, MessagePayload::Handshake { .. }),
391 "QUIC uses TLS for the cryptographic handshake only"
392 );
393 let mut bytes = Vec::new();
394 m.payload.encode(&mut bytes);
395 self.quic
396 .hs_queue
397 .push_back((must_encrypt, bytes));
398 }
399 return;
400 }
401 }
402 if !must_encrypt {
403 let msg = &m.into();
404 let iter = self
405 .message_fragmenter
406 .fragment_message(msg);
407 for m in iter {
408 self.queue_tls_message(m.to_unencrypted_opaque());
409 }
410 } else {
411 self.send_msg_encrypt(m.into());
412 }
413 }
414
415 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload) {
416 self.received_plaintext.append(bytes.0);
417 }
418
419 #[cfg(feature = "tls12")]
420 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
421 let (dec, enc) = secrets.make_cipher_pair(side);
422 self.record_layer
423 .prepare_message_encrypter(enc);
424 self.record_layer
425 .prepare_message_decrypter(dec);
426 }
427
428 #[cfg(feature = "quic")]
429 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
430 self.send_fatal_alert(AlertDescription::MissingExtension, why)
431 }
432
433 fn send_warning_alert(&mut self, desc: AlertDescription) {
434 warn!("Sending warning alert {:?}", desc);
435 self.send_warning_alert_no_log(desc);
436 }
437
438 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
439 if let AlertLevel::Unknown(_) = alert.level {
441 return Err(self.send_fatal_alert(
442 AlertDescription::IllegalParameter,
443 Error::AlertReceived(alert.description),
444 ));
445 }
446
447 if self.may_receive_application_data && alert.description == AlertDescription::CloseNotify {
450 self.has_received_close_notify = true;
451 return Ok(());
452 }
453
454 let err = Error::AlertReceived(alert.description);
457 if alert.level == AlertLevel::Warning {
458 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
459 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
460 } else {
461 warn!("TLS alert warning received: {:#?}", alert);
462 return Ok(());
463 }
464 }
465
466 Err(err)
467 }
468
469 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
470 self.send_fatal_alert(
471 match &err {
472 Error::InvalidCertificate(e) => e.clone().into(),
473 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
474 _ => AlertDescription::HandshakeFailure,
475 },
476 err,
477 )
478 }
479
480 pub(crate) fn send_fatal_alert(
481 &mut self,
482 desc: AlertDescription,
483 err: impl Into<Error>,
484 ) -> Error {
485 debug_assert!(!self.sent_fatal_alert);
486 let m = Message::build_alert(AlertLevel::Fatal, desc);
487 self.send_msg(m, self.record_layer.is_encrypting());
488 self.sent_fatal_alert = true;
489 err.into()
490 }
491
492 pub fn send_close_notify(&mut self) {
498 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
499 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
500 }
501
502 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
503 let m = Message::build_alert(AlertLevel::Warning, desc);
504 self.send_msg(m, self.record_layer.is_encrypting());
505 }
506
507 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
508 self.message_fragmenter
509 .set_max_fragment_size(new)
510 }
511
512 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
513 self.alpn_protocol
514 .as_ref()
515 .map(AsRef::as_ref)
516 }
517
518 pub fn wants_read(&self) -> bool {
528 self.received_plaintext.is_empty()
535 && !self.has_received_close_notify
536 && (self.may_send_application_data || self.sendable_tls.is_empty())
537 }
538
539 pub(crate) fn current_io_state(&self) -> IoState {
540 IoState {
541 tls_bytes_to_write: self.sendable_tls.len(),
542 plaintext_bytes_to_read: self.received_plaintext.len(),
543 peer_has_closed: self.has_received_close_notify,
544 }
545 }
546
547 pub(crate) fn is_quic(&self) -> bool {
548 #[cfg(feature = "quic")]
549 {
550 self.protocol == Protocol::Quic
551 }
552 #[cfg(not(feature = "quic"))]
553 false
554 }
555
556 pub(crate) fn should_update_key(
557 &mut self,
558 key_update_request: &KeyUpdateRequest,
559 ) -> Result<bool, Error> {
560 match key_update_request {
561 KeyUpdateRequest::UpdateNotRequested => Ok(false),
562 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
563 _ => Err(self.send_fatal_alert(
564 AlertDescription::IllegalParameter,
565 InvalidMessage::InvalidKeyUpdate,
566 )),
567 }
568 }
569
570 pub(crate) fn enqueue_key_update_notification(&mut self) {
571 let message = PlainMessage::from(Message::build_key_update_notify());
572 self.queued_key_update_message = Some(
573 self.record_layer
574 .encrypt_outgoing(message.borrow())
575 .encode(),
576 );
577 }
578
579 pub(crate) fn perhaps_write_key_update(&mut self) {
580 if let Some(message) = self.queued_key_update_message.take() {
581 self.sendable_tls.append(message);
582 }
583 }
584}
585
586#[derive(Debug, Eq, PartialEq)]
591pub struct IoState {
592 tls_bytes_to_write: usize,
593 plaintext_bytes_to_read: usize,
594 peer_has_closed: bool,
595}
596
597impl IoState {
598 pub fn tls_bytes_to_write(&self) -> usize {
603 self.tls_bytes_to_write
604 }
605
606 pub fn plaintext_bytes_to_read(&self) -> usize {
609 self.plaintext_bytes_to_read
610 }
611
612 pub fn peer_has_closed(&self) -> bool {
621 self.peer_has_closed
622 }
623}
624
625pub(crate) trait State<Data>: Send + Sync {
626 fn handle(
627 self: Box<Self>,
628 cx: &mut Context<'_, Data>,
629 message: Message,
630 ) -> Result<Box<dyn State<Data>>, Error>;
631
632 fn export_keying_material(
633 &self,
634 _output: &mut [u8],
635 _label: &[u8],
636 _context: Option<&[u8]>,
637 ) -> Result<(), Error> {
638 Err(Error::HandshakeNotComplete)
639 }
640
641 #[cfg(feature = "secret_extraction")]
642 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
643 Err(Error::HandshakeNotComplete)
644 }
645
646 fn handle_decrypt_error(&self) {}
647}
648
649pub(crate) struct Context<'a, Data> {
650 pub(crate) common: &'a mut CommonState,
651 pub(crate) data: &'a mut Data,
652}
653
654#[derive(Clone, Copy, Debug, PartialEq)]
656pub enum Side {
657 Client,
659 Server,
661}
662
663impl Side {
664 pub(crate) fn peer(&self) -> Self {
665 match self {
666 Self::Client => Self::Server,
667 Self::Server => Self::Client,
668 }
669 }
670}
671
672#[derive(Copy, Clone, Eq, PartialEq, Debug)]
673pub(crate) enum Protocol {
674 Tcp,
675 #[cfg(feature = "quic")]
676 Quic,
677}
678
679enum Limit {
680 Yes,
681 No,
682}
683
684const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
685const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;