1use crate::enums::{AlertDescription, ContentType, HandshakeType, ProtocolVersion};
2use crate::error::{Error, InvalidMessage, PeerMisbehaved};
3#[cfg(feature = "logging")]
4use crate::log::{debug, warn};
5use crate::msgs::alert::AlertMessagePayload;
6use crate::msgs::base::Payload;
7use crate::msgs::enums::{AlertLevel, KeyUpdateRequest};
8use crate::msgs::fragmenter::MessageFragmenter;
9use crate::msgs::handshake::CertificateChain;
10use crate::msgs::message::MessagePayload;
11use crate::msgs::message::{BorrowedPlainMessage, Message, OpaqueMessage, PlainMessage};
12use crate::quic;
13use crate::record_layer;
14use crate::suites::PartiallyExtractedSecrets;
15use crate::suites::SupportedCipherSuite;
16#[cfg(feature = "tls12")]
17use crate::tls12::ConnectionSecrets;
18use crate::vecbuf::ChunkVecBuffer;
19
20use alloc::boxed::Box;
21use alloc::vec::Vec;
22
23use pki_types::CertificateDer;
24
25pub struct CommonState {
27 pub(crate) negotiated_version: Option<ProtocolVersion>,
28 pub(crate) side: Side,
29 pub(crate) record_layer: record_layer::RecordLayer,
30 pub(crate) suite: Option<SupportedCipherSuite>,
31 pub(crate) alpn_protocol: Option<Vec<u8>>,
32 pub(crate) aligned_handshake: bool,
33 pub(crate) may_send_application_data: bool,
34 pub(crate) may_receive_application_data: bool,
35 pub(crate) early_traffic: bool,
36 sent_fatal_alert: bool,
37 pub(crate) has_received_close_notify: bool,
39 pub(crate) has_seen_eof: bool,
40 pub(crate) received_middlebox_ccs: u8,
41 pub(crate) peer_certificates: Option<CertificateChain>,
42 message_fragmenter: MessageFragmenter,
43 pub(crate) received_plaintext: ChunkVecBuffer,
44 sendable_plaintext: ChunkVecBuffer,
45 pub(crate) sendable_tls: ChunkVecBuffer,
46 pub(crate) certificate_compression_algorithm: Option<crate::CertificateCompressionAlgorithm>,
47 queued_key_update_message: Option<Vec<u8>>,
48
49 pub(crate) protocol: Protocol,
51 pub(crate) quic: quic::Quic,
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 certificate_compression_algorithm: None,
77 queued_key_update_message: None,
78 protocol: Protocol::Tcp,
79 quic: quic::Quic::default(),
80 enable_secret_extraction: false,
81 }
82 }
83
84 pub fn wants_write(&self) -> bool {
88 !self.sendable_tls.is_empty()
89 }
90
91 pub fn is_handshaking(&self) -> bool {
99 !(self.may_send_application_data && self.may_receive_application_data)
100 }
101
102 pub fn peer_certificates(&self) -> Option<&[CertificateDer<'_>]> {
118 self.peer_certificates.as_deref()
119 }
120
121 pub fn alpn_protocol(&self) -> Option<&[u8]> {
127 self.get_alpn_protocol()
128 }
129
130 pub fn negotiated_cipher_suite(&self) -> Option<SupportedCipherSuite> {
134 self.suite
135 }
136
137 pub fn protocol_version(&self) -> Option<ProtocolVersion> {
141 self.negotiated_version
142 }
143
144 pub(crate) fn is_tls13(&self) -> bool {
145 matches!(self.negotiated_version, Some(ProtocolVersion::TLSv1_3))
146 }
147
148 pub(crate) fn process_main_protocol<Data>(
149 &mut self,
150 msg: Message,
151 mut state: Box<dyn State<Data>>,
152 data: &mut Data,
153 ) -> Result<Box<dyn State<Data>>, Error> {
154 if self.may_receive_application_data && !self.is_tls13() {
157 let reject_ty = match self.side {
158 Side::Client => HandshakeType::HelloRequest,
159 Side::Server => HandshakeType::ClientHello,
160 };
161 if msg.is_handshake_type(reject_ty) {
162 self.send_warning_alert(AlertDescription::NoRenegotiation);
163 return Ok(state);
164 }
165 }
166
167 let mut cx = Context { common: self, data };
168 match state.handle(&mut cx, msg) {
169 Ok(next) => {
170 state = next;
171 Ok(state)
172 }
173 Err(e @ Error::InappropriateMessage { .. })
174 | Err(e @ Error::InappropriateHandshakeMessage { .. }) => {
175 Err(self.send_fatal_alert(AlertDescription::UnexpectedMessage, e))
176 }
177 Err(e) => Err(e),
178 }
179 }
180
181 pub(crate) fn send_some_plaintext(&mut self, data: &[u8]) -> usize {
187 self.perhaps_write_key_update();
188 self.send_plain(data, Limit::Yes)
189 }
190
191 pub(crate) fn send_early_plaintext(&mut self, data: &[u8]) -> usize {
192 debug_assert!(self.early_traffic);
193 debug_assert!(self.record_layer.is_encrypting());
194
195 if data.is_empty() {
196 return 0;
198 }
199
200 self.send_appdata_encrypt(data, Limit::Yes)
201 }
202
203 pub(crate) fn check_aligned_handshake(&mut self) -> Result<(), Error> {
208 if !self.aligned_handshake {
209 Err(self.send_fatal_alert(
210 AlertDescription::UnexpectedMessage,
211 PeerMisbehaved::KeyEpochWithPendingFragment,
212 ))
213 } else {
214 Ok(())
215 }
216 }
217
218 pub(crate) fn send_msg_encrypt(&mut self, m: PlainMessage) {
221 let iter = self
222 .message_fragmenter
223 .fragment_message(&m);
224 for m in iter {
225 self.send_single_fragment(m);
226 }
227 }
228
229 fn send_appdata_encrypt(&mut self, payload: &[u8], limit: Limit) -> usize {
231 let len = match limit {
236 Limit::Yes => self
237 .sendable_tls
238 .apply_limit(payload.len()),
239 Limit::No => payload.len(),
240 };
241
242 let iter = self.message_fragmenter.fragment_slice(
243 ContentType::ApplicationData,
244 ProtocolVersion::TLSv1_2,
245 &payload[..len],
246 );
247 for m in iter {
248 self.send_single_fragment(m);
249 }
250
251 len
252 }
253
254 fn send_single_fragment(&mut self, m: BorrowedPlainMessage) {
255 if self
258 .record_layer
259 .wants_close_before_encrypt()
260 {
261 self.send_close_notify();
262 }
263
264 if self.record_layer.encrypt_exhausted() {
267 return;
268 }
269
270 let em = self.record_layer.encrypt_outgoing(m);
271 self.queue_tls_message(em);
272 }
273
274 fn send_plain(&mut self, data: &[u8], limit: Limit) -> usize {
280 if !self.may_send_application_data {
281 let len = match limit {
284 Limit::Yes => self
285 .sendable_plaintext
286 .append_limited_copy(data),
287 Limit::No => self
288 .sendable_plaintext
289 .append(data.to_vec()),
290 };
291 return len;
292 }
293
294 debug_assert!(self.record_layer.is_encrypting());
295
296 if data.is_empty() {
297 return 0;
299 }
300
301 self.send_appdata_encrypt(data, limit)
302 }
303
304 pub(crate) fn start_outgoing_traffic(&mut self) {
305 self.may_send_application_data = true;
306 self.flush_plaintext();
307 }
308
309 pub(crate) fn start_traffic(&mut self) {
310 self.may_receive_application_data = true;
311 self.start_outgoing_traffic();
312 }
313
314 pub fn set_buffer_limit(&mut self, limit: Option<usize>) {
358 self.sendable_plaintext.set_limit(limit);
359 self.sendable_tls.set_limit(limit);
360 }
361
362 fn flush_plaintext(&mut self) {
365 if !self.may_send_application_data {
366 return;
367 }
368
369 while let Some(buf) = self.sendable_plaintext.pop() {
370 self.send_plain(&buf, Limit::No);
371 }
372 }
373
374 fn queue_tls_message(&mut self, m: OpaqueMessage) {
376 self.sendable_tls.append(m.encode());
377 }
378
379 pub(crate) fn send_msg(&mut self, m: Message, must_encrypt: bool) {
381 {
382 if let Protocol::Quic = self.protocol {
383 if let MessagePayload::Alert(alert) = m.payload {
384 self.quic.alert = Some(alert.description);
385 } else {
386 debug_assert!(
387 matches!(m.payload, MessagePayload::Handshake { .. }),
388 "QUIC uses TLS for the cryptographic handshake only"
389 );
390 let mut bytes = Vec::new();
391 m.payload.encode(&mut bytes);
392 self.quic
393 .hs_queue
394 .push_back((must_encrypt, bytes));
395 }
396 return;
397 }
398 }
399 if !must_encrypt {
400 let msg = &m.into();
401 let iter = self
402 .message_fragmenter
403 .fragment_message(msg);
404 for m in iter {
405 self.queue_tls_message(m.to_unencrypted_opaque());
406 }
407 } else {
408 self.send_msg_encrypt(m.into());
409 }
410 }
411
412 pub(crate) fn take_received_plaintext(&mut self, bytes: Payload) {
413 self.received_plaintext.append(bytes.0);
414 }
415
416 #[cfg(feature = "tls12")]
417 pub(crate) fn start_encryption_tls12(&mut self, secrets: &ConnectionSecrets, side: Side) {
418 let (dec, enc) = secrets.make_cipher_pair(side);
419 self.record_layer
420 .prepare_message_encrypter(enc);
421 self.record_layer
422 .prepare_message_decrypter(dec);
423 }
424
425 pub(crate) fn missing_extension(&mut self, why: PeerMisbehaved) -> Error {
426 self.send_fatal_alert(AlertDescription::MissingExtension, why)
427 }
428
429 fn send_warning_alert(&mut self, desc: AlertDescription) {
430 warn!("Sending warning alert {:?}", desc);
431 self.send_warning_alert_no_log(desc);
432 }
433
434 pub(crate) fn process_alert(&mut self, alert: &AlertMessagePayload) -> Result<(), Error> {
435 if let AlertLevel::Unknown(_) = alert.level {
437 return Err(self.send_fatal_alert(
438 AlertDescription::IllegalParameter,
439 Error::AlertReceived(alert.description),
440 ));
441 }
442
443 if alert.description == AlertDescription::CloseNotify {
446 self.has_received_close_notify = true;
447 return Ok(());
448 }
449
450 let err = Error::AlertReceived(alert.description);
453 if alert.level == AlertLevel::Warning {
454 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
455 return Err(self.send_fatal_alert(AlertDescription::DecodeError, err));
456 } else {
457 warn!("TLS alert warning received: {:#?}", alert);
458 return Ok(());
459 }
460 }
461
462 Err(err)
463 }
464
465 pub(crate) fn send_cert_verify_error_alert(&mut self, err: Error) -> Error {
466 self.send_fatal_alert(
467 match &err {
468 Error::InvalidCertificate(e) => e.clone().into(),
469 Error::PeerMisbehaved(_) => AlertDescription::IllegalParameter,
470 _ => AlertDescription::HandshakeFailure,
471 },
472 err,
473 )
474 }
475
476 pub(crate) fn send_fatal_alert(
477 &mut self,
478 desc: AlertDescription,
479 err: impl Into<Error>,
480 ) -> Error {
481 debug_assert!(!self.sent_fatal_alert);
482 let m = Message::build_alert(AlertLevel::Fatal, desc);
483 self.send_msg(m, self.record_layer.is_encrypting());
484 self.sent_fatal_alert = true;
485 err.into()
486 }
487
488 pub fn send_close_notify(&mut self) {
494 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
495 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
496 }
497
498 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
499 let m = Message::build_alert(AlertLevel::Warning, desc);
500 self.send_msg(m, self.record_layer.is_encrypting());
501 }
502
503 pub(crate) fn set_max_fragment_size(&mut self, new: Option<usize>) -> Result<(), Error> {
504 self.message_fragmenter
505 .set_max_fragment_size(new)
506 }
507
508 pub(crate) fn get_alpn_protocol(&self) -> Option<&[u8]> {
509 self.alpn_protocol
510 .as_ref()
511 .map(AsRef::as_ref)
512 }
513
514 pub fn wants_read(&self) -> bool {
524 self.received_plaintext.is_empty()
531 && !self.has_received_close_notify
532 && (self.may_send_application_data || self.sendable_tls.is_empty())
533 }
534
535 pub(crate) fn current_io_state(&self) -> IoState {
536 IoState {
537 tls_bytes_to_write: self.sendable_tls.len(),
538 plaintext_bytes_to_read: self.received_plaintext.len(),
539 peer_has_closed: self.has_received_close_notify,
540 }
541 }
542
543 pub(crate) fn is_quic(&self) -> bool {
544 self.protocol == Protocol::Quic
545 }
546
547 pub(crate) fn should_update_key(
548 &mut self,
549 key_update_request: &KeyUpdateRequest,
550 ) -> Result<bool, Error> {
551 match key_update_request {
552 KeyUpdateRequest::UpdateNotRequested => Ok(false),
553 KeyUpdateRequest::UpdateRequested => Ok(self.queued_key_update_message.is_none()),
554 _ => Err(self.send_fatal_alert(
555 AlertDescription::IllegalParameter,
556 InvalidMessage::InvalidKeyUpdate,
557 )),
558 }
559 }
560
561 pub(crate) fn enqueue_key_update_notification(&mut self) {
562 let message = PlainMessage::from(Message::build_key_update_notify());
563 self.queued_key_update_message = Some(
564 self.record_layer
565 .encrypt_outgoing(message.borrow())
566 .encode(),
567 );
568 }
569
570 pub(crate) fn perhaps_write_key_update(&mut self) {
571 if let Some(message) = self.queued_key_update_message.take() {
572 self.sendable_tls.append(message);
573 }
574 }
575}
576
577#[derive(Debug, Eq, PartialEq)]
582pub struct IoState {
583 tls_bytes_to_write: usize,
584 plaintext_bytes_to_read: usize,
585 peer_has_closed: bool,
586}
587
588impl IoState {
589 pub fn tls_bytes_to_write(&self) -> usize {
594 self.tls_bytes_to_write
595 }
596
597 pub fn plaintext_bytes_to_read(&self) -> usize {
600 self.plaintext_bytes_to_read
601 }
602
603 pub fn peer_has_closed(&self) -> bool {
612 self.peer_has_closed
613 }
614}
615
616pub(crate) trait State<Data>: Send + Sync {
617 fn handle(
618 self: Box<Self>,
619 cx: &mut Context<'_, Data>,
620 message: Message,
621 ) -> Result<Box<dyn State<Data>>, Error>;
622
623 fn export_keying_material(
624 &self,
625 _output: &mut [u8],
626 _label: &[u8],
627 _context: Option<&[u8]>,
628 ) -> Result<(), Error> {
629 Err(Error::HandshakeNotComplete)
630 }
631
632 fn extract_secrets(&self) -> Result<PartiallyExtractedSecrets, Error> {
633 Err(Error::HandshakeNotComplete)
634 }
635}
636
637pub(crate) struct Context<'a, Data> {
638 pub(crate) common: &'a mut CommonState,
639 pub(crate) data: &'a mut Data,
640}
641
642#[derive(Clone, Copy, Debug, PartialEq)]
644pub enum Side {
645 Client,
647 Server,
649}
650
651impl Side {
652 pub(crate) fn peer(&self) -> Self {
653 match self {
654 Self::Client => Self::Server,
655 Self::Server => Self::Client,
656 }
657 }
658}
659
660#[derive(Copy, Clone, Eq, PartialEq, Debug)]
661pub(crate) enum Protocol {
662 Tcp,
663 Quic,
664}
665
666enum Limit {
667 Yes,
668 No,
669}
670
671const DEFAULT_RECEIVED_PLAINTEXT_LIMIT: usize = 16 * 1024;
672const DEFAULT_BUFFER_LIMIT: usize = 64 * 1024;