1 use ring;
2 use std::io::{Read, Write};
3 use crate::msgs::message::{BorrowMessage, Message, MessagePayload};
4 use crate::msgs::deframer::MessageDeframer;
5 use crate::msgs::fragmenter::{MessageFragmenter, MAX_FRAGMENT_LEN};
6 use crate::msgs::hsjoiner::HandshakeJoiner;
7 use crate::msgs::base::Payload;
8 use crate::msgs::codec::Codec;
9 use crate::msgs::enums::{ContentType, ProtocolVersion, AlertDescription, AlertLevel};
10 use crate::error::TLSError;
11 use crate::suites::SupportedCipherSuite;
12 use crate::cipher;
13 use crate::vecbuf::ChunkVecBuffer;
14 use crate::key;
15 use crate::prf;
16 use crate::rand;
17 use crate::quic;
18 use crate::record_layer;
19 #[cfg(feature = "logging")]
20 use crate::log::{warn, debug, error};
21
22 use std::io;
23 use std::collections::VecDeque;
24
25 /// Generalises `ClientSession` and `ServerSession`
26 pub trait Session: quic::QuicExt + Read + Write + Send + Sync {
27 /// Read TLS content from `rd`. This method does internal
28 /// buffering, so `rd` can supply TLS messages in arbitrary-
29 /// sized chunks (like a socket or pipe might).
30 ///
31 /// You should call `process_new_packets` each time a call to
32 /// this function succeeds.
33 ///
34 /// The returned error only relates to IO on `rd`. TLS-level
35 /// errors are emitted from `process_new_packets`.
36 ///
37 /// This function returns `Ok(0)` when the underlying `rd` does
38 /// so. This typically happens when a socket is cleanly closed,
39 /// or a file is at EOF.
read_tls(&mut self, rd: &mut dyn Read) -> Result<usize, io::Error>40 fn read_tls(&mut self, rd: &mut dyn Read) -> Result<usize, io::Error>;
41
42 /// Writes TLS messages to `wr`.
43 ///
44 /// On success the function returns `Ok(n)` where `n` is a number
45 /// of bytes written to `wr`, number of bytes after encoding and
46 /// encryption.
47 ///
48 /// Note that after function return the session buffer maybe not
49 /// yet fully flushed. [`wants_write`] function can be used
50 /// to check if output buffer is not empty.
51 ///
52 /// [`wants_write`]: #tymethod.wants_write
write_tls(&mut self, wr: &mut dyn Write) -> Result<usize, io::Error>53 fn write_tls(&mut self, wr: &mut dyn Write) -> Result<usize, io::Error>;
54
55 /// Processes any new packets read by a previous call to `read_tls`.
56 /// Errors from this function relate to TLS protocol errors, and
57 /// are fatal to the session. Future calls after an error will do
58 /// no new work and will return the same error.
59 ///
60 /// Success from this function can mean new plaintext is available:
61 /// obtain it using `read`.
process_new_packets(&mut self) -> Result<(), TLSError>62 fn process_new_packets(&mut self) -> Result<(), TLSError>;
63
64 /// Returns true if the caller should call `read_tls` as soon
65 /// as possible.
wants_read(&self) -> bool66 fn wants_read(&self) -> bool;
67
68 /// Returns true if the caller should call `write_tls` as soon
69 /// as possible.
wants_write(&self) -> bool70 fn wants_write(&self) -> bool;
71
72 /// Returns true if the session is currently perform the TLS
73 /// handshake. During this time plaintext written to the
74 /// session is buffered in memory.
is_handshaking(&self) -> bool75 fn is_handshaking(&self) -> bool;
76
77 /// Sets a limit on the internal buffers used to buffer
78 /// unsent plaintext (prior to completing the TLS handshake)
79 /// and unsent TLS records.
80 ///
81 /// By default, there is no limit. The limit can be set
82 /// at any time, even if the current buffer use is higher.
set_buffer_limit(&mut self, limit: usize)83 fn set_buffer_limit(&mut self, limit: usize);
84
85 /// Queues a close_notify fatal alert to be sent in the next
86 /// `write_tls` call. This informs the peer that the
87 /// connection is being closed.
send_close_notify(&mut self)88 fn send_close_notify(&mut self);
89
90 /// Retrieves the certificate chain used by the peer to authenticate.
91 ///
92 /// For clients, this is the certificate chain of the server.
93 ///
94 /// For servers, this is the certificate chain of the client,
95 /// if client authentication was completed.
96 ///
97 /// The return value is None until this value is available.
get_peer_certificates(&self) -> Option<Vec<key::Certificate>>98 fn get_peer_certificates(&self) -> Option<Vec<key::Certificate>>;
99
100 /// Retrieves the protocol agreed with the peer via ALPN.
101 ///
102 /// A return value of None after handshake completion
103 /// means no protocol was agreed (because no protocols
104 /// were offered or accepted by the peer).
get_alpn_protocol(&self) -> Option<&[u8]>105 fn get_alpn_protocol(&self) -> Option<&[u8]>;
106
107 /// Retrieves the protocol version agreed with the peer.
108 ///
109 /// This returns None until the version is agreed.
get_protocol_version(&self) -> Option<ProtocolVersion>110 fn get_protocol_version(&self) -> Option<ProtocolVersion>;
111
112 /// Derives key material from the agreed session secrets.
113 ///
114 /// This function fills in `output` with `output.len()` bytes of key
115 /// material derived from the master session secret using `label`
116 /// and `context` for diversification.
117 ///
118 /// See RFC5705 for more details on what this does and is for.
119 ///
120 /// For TLS1.3 connections, this function does not use the
121 /// "early" exporter at any point.
122 ///
123 /// This function fails if called prior to the handshake completing;
124 /// check with `is_handshaking()` first.
export_keying_material(&self, output: &mut [u8], label: &[u8], context: Option<&[u8]>) -> Result<(), TLSError>125 fn export_keying_material(&self,
126 output: &mut [u8],
127 label: &[u8],
128 context: Option<&[u8]>) -> Result<(), TLSError>;
129
130 /// Retrieves the ciphersuite agreed with the peer.
131 ///
132 /// This returns None until the ciphersuite is agreed.
get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite>133 fn get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite>;
134
135 /// This function uses `io` to complete any outstanding IO for
136 /// this session.
137 ///
138 /// This is a convenience function which solely uses other parts
139 /// of the public API.
140 ///
141 /// What this means depends on the session state:
142 ///
143 /// - If the session `is_handshaking()`, then IO is performed until
144 /// the handshake is complete.
145 /// - Otherwise, if `wants_write` is true, `write_tls` is invoked
146 /// until it is all written.
147 /// - Otherwise, if `wants_read` is true, `read_tls` is invoked
148 /// once.
149 ///
150 /// The return value is the number of bytes read from and written
151 /// to `io`, respectively.
152 ///
153 /// This function will block if `io` blocks.
154 ///
155 /// Errors from TLS record handling (ie, from `process_new_packets()`)
156 /// are wrapped in an `io::ErrorKind::InvalidData`-kind error.
complete_io<T>(&mut self, io: &mut T) -> Result<(usize, usize), io::Error> where Self: Sized, T: Read + Write157 fn complete_io<T>(&mut self, io: &mut T) -> Result<(usize, usize), io::Error>
158 where Self: Sized, T: Read + Write
159 {
160 let until_handshaked = self.is_handshaking();
161 let mut eof = false;
162 let mut wrlen = 0;
163 let mut rdlen = 0;
164
165 loop {
166 while self.wants_write() {
167 wrlen += self.write_tls(io)?;
168 }
169
170 if !until_handshaked && wrlen > 0 {
171 return Ok((rdlen, wrlen));
172 }
173
174 if !eof && self.wants_read() {
175 match self.read_tls(io)? {
176 0 => eof = true,
177 n => rdlen += n
178 }
179 }
180
181 match self.process_new_packets() {
182 Ok(_) => {},
183 Err(e) => {
184 // In case we have an alert to send describing this error,
185 // try a last-gasp write -- but don't predate the primary
186 // error.
187 let _ignored = self.write_tls(io);
188
189 return Err(io::Error::new(io::ErrorKind::InvalidData, e));
190 },
191 };
192
193 match (eof, until_handshaked, self.is_handshaking()) {
194 (_, true, false) => return Ok((rdlen, wrlen)),
195 (_, false, _) => return Ok((rdlen, wrlen)),
196 (true, true, true) => return Err(io::Error::from(io::ErrorKind::UnexpectedEof)),
197 (..) => ()
198 }
199 }
200 }
201 }
202
203 #[derive(Copy, Clone, Eq, PartialEq)]
204 pub enum Protocol {
205 Tls13,
206 #[cfg(feature = "quic")]
207 Quic,
208 }
209
210 #[derive(Clone, Debug)]
211 pub struct SessionRandoms {
212 pub we_are_client: bool,
213 pub client: [u8; 32],
214 pub server: [u8; 32],
215 }
216
217 static TLS12_DOWNGRADE_SENTINEL: &[u8] = &[0x44, 0x4f, 0x57, 0x4e, 0x47, 0x52, 0x44, 0x01];
218
219 impl SessionRandoms {
for_server() -> SessionRandoms220 pub fn for_server() -> SessionRandoms {
221 let mut ret = SessionRandoms {
222 we_are_client: false,
223 client: [0u8; 32],
224 server: [0u8; 32],
225 };
226
227 rand::fill_random(&mut ret.server);
228 ret
229 }
230
for_client() -> SessionRandoms231 pub fn for_client() -> SessionRandoms {
232 let mut ret = SessionRandoms {
233 we_are_client: true,
234 client: [0u8; 32],
235 server: [0u8; 32],
236 };
237
238 rand::fill_random(&mut ret.client);
239 ret
240 }
241
set_tls12_downgrade_marker(&mut self)242 pub fn set_tls12_downgrade_marker(&mut self) {
243 assert!(!self.we_are_client);
244 self.server[24..]
245 .as_mut()
246 .write_all(TLS12_DOWNGRADE_SENTINEL)
247 .unwrap();
248 }
249
has_tls12_downgrade_marker(&mut self) -> bool250 pub fn has_tls12_downgrade_marker(&mut self) -> bool {
251 assert!(self.we_are_client);
252 // both the server random and TLS12_DOWNGRADE_SENTINEL are
253 // public values and don't require constant time comparison
254 &self.server[24..] == TLS12_DOWNGRADE_SENTINEL
255 }
256 }
257
join_randoms(first: &[u8], second: &[u8]) -> [u8; 64]258 fn join_randoms(first: &[u8], second: &[u8]) -> [u8; 64] {
259 let mut randoms = [0u8; 64];
260 randoms.as_mut().write_all(first).unwrap();
261 randoms[32..].as_mut().write_all(second).unwrap();
262 randoms
263 }
264
265 /// TLS1.2 per-session keying material
266 pub struct SessionSecrets {
267 pub randoms: SessionRandoms,
268 hash: &'static ring::digest::Algorithm,
269 pub master_secret: [u8; 48],
270 }
271
272 impl SessionSecrets {
new(randoms: &SessionRandoms, hashalg: &'static ring::digest::Algorithm, pms: &[u8]) -> SessionSecrets273 pub fn new(randoms: &SessionRandoms,
274 hashalg: &'static ring::digest::Algorithm,
275 pms: &[u8])
276 -> SessionSecrets {
277 let mut ret = SessionSecrets {
278 randoms: randoms.clone(),
279 hash: hashalg,
280 master_secret: [0u8; 48],
281 };
282
283 let randoms = join_randoms(&ret.randoms.client, &ret.randoms.server);
284 prf::prf(&mut ret.master_secret,
285 ret.hash,
286 pms,
287 b"master secret",
288 &randoms);
289 ret
290 }
291
new_ems(randoms: &SessionRandoms, hs_hash: &[u8], hashalg: &'static ring::digest::Algorithm, pms: &[u8]) -> SessionSecrets292 pub fn new_ems(randoms: &SessionRandoms,
293 hs_hash: &[u8],
294 hashalg: &'static ring::digest::Algorithm,
295 pms: &[u8]) -> SessionSecrets {
296 let mut ret = SessionSecrets {
297 randoms: randoms.clone(),
298 hash: hashalg,
299 master_secret: [0u8; 48]
300 };
301
302 prf::prf(&mut ret.master_secret,
303 ret.hash,
304 pms,
305 b"extended master secret",
306 hs_hash);
307 ret
308 }
309
new_resume(randoms: &SessionRandoms, hashalg: &'static ring::digest::Algorithm, master_secret: &[u8]) -> SessionSecrets310 pub fn new_resume(randoms: &SessionRandoms,
311 hashalg: &'static ring::digest::Algorithm,
312 master_secret: &[u8])
313 -> SessionSecrets {
314 let mut ret = SessionSecrets {
315 randoms: randoms.clone(),
316 hash: hashalg,
317 master_secret: [0u8; 48],
318 };
319 ret.master_secret.as_mut().write_all(master_secret).unwrap();
320 ret
321 }
322
make_key_block(&self, len: usize) -> Vec<u8>323 pub fn make_key_block(&self, len: usize) -> Vec<u8> {
324 let mut out = Vec::new();
325 out.resize(len, 0u8);
326
327 // NOTE: opposite order to above for no good reason.
328 // Don't design security protocols on drugs, kids.
329 let randoms = join_randoms(&self.randoms.server, &self.randoms.client);
330 prf::prf(&mut out,
331 self.hash,
332 &self.master_secret,
333 b"key expansion",
334 &randoms);
335
336 out
337 }
338
get_master_secret(&self) -> Vec<u8>339 pub fn get_master_secret(&self) -> Vec<u8> {
340 let mut ret = Vec::new();
341 ret.extend_from_slice(&self.master_secret);
342 ret
343 }
344
make_verify_data(&self, handshake_hash: &[u8], label: &[u8]) -> Vec<u8>345 pub fn make_verify_data(&self, handshake_hash: &[u8], label: &[u8]) -> Vec<u8> {
346 let mut out = Vec::new();
347 out.resize(12, 0u8);
348
349 prf::prf(&mut out,
350 self.hash,
351 &self.master_secret,
352 label,
353 handshake_hash);
354 out
355 }
356
client_verify_data(&self, handshake_hash: &[u8]) -> Vec<u8>357 pub fn client_verify_data(&self, handshake_hash: &[u8]) -> Vec<u8> {
358 self.make_verify_data(handshake_hash, b"client finished")
359 }
360
server_verify_data(&self, handshake_hash: &[u8]) -> Vec<u8>361 pub fn server_verify_data(&self, handshake_hash: &[u8]) -> Vec<u8> {
362 self.make_verify_data(handshake_hash, b"server finished")
363 }
364
export_keying_material(&self, output: &mut [u8], label: &[u8], context: Option<&[u8]>)365 pub fn export_keying_material(&self,
366 output: &mut [u8],
367 label: &[u8],
368 context: Option<&[u8]>) {
369 let mut randoms = Vec::new();
370 randoms.extend_from_slice(&self.randoms.client);
371 randoms.extend_from_slice(&self.randoms.server);
372 if let Some(context) = context {
373 assert!(context.len() <= 0xffff);
374 (context.len() as u16).encode(&mut randoms);
375 randoms.extend_from_slice(context);
376 }
377
378 prf::prf(output,
379 self.hash,
380 &self.master_secret,
381 label,
382 &randoms)
383 }
384 }
385
386 // --- Common (to client and server) session functions ---
387
388 enum Limit {
389 Yes,
390 No
391 }
392
393 /// For TLS1.3 middlebox compatibility mode, how to handle
394 /// a received ChangeCipherSpec message.
395 pub enum MiddleboxCCS {
396 /// process the message as normal
397 Process,
398
399 /// just ignore it
400 Drop,
401 }
402
403 pub struct SessionCommon {
404 pub negotiated_version: Option<ProtocolVersion>,
405 pub is_client: bool,
406 pub record_layer: record_layer::RecordLayer,
407 suite: Option<&'static SupportedCipherSuite>,
408 peer_eof: bool,
409 pub traffic: bool,
410 pub early_traffic: bool,
411 sent_fatal_alert: bool,
412 received_middlebox_ccs: bool,
413 pub message_deframer: MessageDeframer,
414 pub handshake_joiner: HandshakeJoiner,
415 pub message_fragmenter: MessageFragmenter,
416 received_plaintext: ChunkVecBuffer,
417 sendable_plaintext: ChunkVecBuffer,
418 pub sendable_tls: ChunkVecBuffer,
419 /// Protocol whose key schedule should be used. Unused for TLS < 1.3.
420 pub protocol: Protocol,
421 #[cfg(feature = "quic")]
422 pub(crate) quic: Quic,
423 }
424
425 impl SessionCommon {
new(mtu: Option<usize>, client: bool) -> SessionCommon426 pub fn new(mtu: Option<usize>, client: bool) -> SessionCommon {
427 SessionCommon {
428 negotiated_version: None,
429 is_client: client,
430 record_layer: record_layer::RecordLayer::new(),
431 suite: None,
432 peer_eof: false,
433 traffic: false,
434 early_traffic: false,
435 sent_fatal_alert: false,
436 received_middlebox_ccs: false,
437 message_deframer: MessageDeframer::new(),
438 handshake_joiner: HandshakeJoiner::new(),
439 message_fragmenter: MessageFragmenter::new(mtu.unwrap_or(MAX_FRAGMENT_LEN)),
440 received_plaintext: ChunkVecBuffer::new(),
441 sendable_plaintext: ChunkVecBuffer::new(),
442 sendable_tls: ChunkVecBuffer::new(),
443 protocol: Protocol::Tls13,
444 #[cfg(feature = "quic")]
445 quic: Quic::new(),
446 }
447 }
448
is_tls13(&self) -> bool449 pub fn is_tls13(&self) -> bool {
450 match self.negotiated_version {
451 Some(ProtocolVersion::TLSv1_3) => true,
452 _ => false
453 }
454 }
455
get_suite(&self) -> Option<&'static SupportedCipherSuite>456 pub fn get_suite(&self) -> Option<&'static SupportedCipherSuite> {
457 self.suite
458 }
459
get_suite_assert(&self) -> &'static SupportedCipherSuite460 pub fn get_suite_assert(&self) -> &'static SupportedCipherSuite {
461 self.suite.as_ref().unwrap()
462 }
463
set_suite(&mut self, suite: &'static SupportedCipherSuite) -> bool464 pub fn set_suite(&mut self, suite: &'static SupportedCipherSuite) -> bool {
465 match self.suite {
466 None => {
467 self.suite = Some(suite);
468 true
469 }
470 Some(s) if s == suite => {
471 self.suite = Some(suite);
472 true
473 }
474 _ => false
475 }
476 }
477
filter_tls13_ccs(&mut self, msg: &Message) -> Result<MiddleboxCCS, TLSError>478 pub fn filter_tls13_ccs(&mut self, msg: &Message) -> Result<MiddleboxCCS, TLSError> {
479 // pass message to handshake state machine if any of these are true:
480 // - TLS1.2 (where it's part of the state machine),
481 // - prior to determining the version (it's illegal as a first message)
482 // - if it's not a CCS at all
483 // - if we've finished the handshake
484 if !self.is_tls13() ||
485 !msg.is_content_type(ContentType::ChangeCipherSpec) ||
486 self.traffic {
487 return Ok(MiddleboxCCS::Process);
488 }
489
490 if self.received_middlebox_ccs {
491 Err(TLSError::PeerMisbehavedError("illegal middlebox CCS received".into()))
492 } else {
493 self.received_middlebox_ccs = true;
494 Ok(MiddleboxCCS::Drop)
495 }
496 }
497
decrypt_incoming(&mut self, encr: Message) -> Result<Message, TLSError>498 pub fn decrypt_incoming(&mut self, encr: Message) -> Result<Message, TLSError> {
499 if self.record_layer.wants_close_before_decrypt() {
500 self.send_close_notify();
501 }
502
503 let rc = self.record_layer.decrypt_incoming(encr);
504 if let Err(TLSError::PeerSentOversizedRecord) = rc {
505 self.send_fatal_alert(AlertDescription::RecordOverflow);
506 }
507 rc
508 }
509
has_readable_plaintext(&self) -> bool510 pub fn has_readable_plaintext(&self) -> bool {
511 !self.received_plaintext.is_empty()
512 }
513
set_buffer_limit(&mut self, limit: usize)514 pub fn set_buffer_limit(&mut self, limit: usize) {
515 self.sendable_plaintext.set_limit(limit);
516 self.sendable_tls.set_limit(limit);
517 }
518
process_alert(&mut self, msg: Message) -> Result<(), TLSError>519 pub fn process_alert(&mut self, msg: Message) -> Result<(), TLSError> {
520 if let MessagePayload::Alert(ref alert) = msg.payload {
521 // Reject unknown AlertLevels.
522 if let AlertLevel::Unknown(_) = alert.level {
523 self.send_fatal_alert(AlertDescription::IllegalParameter);
524 }
525
526 // If we get a CloseNotify, make a note to declare EOF to our
527 // caller.
528 if alert.description == AlertDescription::CloseNotify {
529 self.peer_eof = true;
530 return Ok(());
531 }
532
533 // Warnings are nonfatal for TLS1.2, but outlawed in TLS1.3
534 // (except, for no good reason, user_cancelled).
535 if alert.level == AlertLevel::Warning {
536 if self.is_tls13() && alert.description != AlertDescription::UserCanceled {
537 self.send_fatal_alert(AlertDescription::DecodeError);
538 } else {
539 warn!("TLS alert warning received: {:#?}", msg);
540 return Ok(());
541 }
542 }
543
544 error!("TLS alert received: {:#?}", msg);
545 Err(TLSError::AlertReceived(alert.description))
546 } else {
547 Err(TLSError::CorruptMessagePayload(ContentType::Alert))
548 }
549 }
550
551 /// Fragment `m`, encrypt the fragments, and then queue
552 /// the encrypted fragments for sending.
send_msg_encrypt(&mut self, m: Message)553 pub fn send_msg_encrypt(&mut self, m: Message) {
554 let mut plain_messages = VecDeque::new();
555 self.message_fragmenter.fragment(m, &mut plain_messages);
556
557 for m in plain_messages {
558 self.send_single_fragment(m.to_borrowed());
559 }
560 }
561
562 /// Like send_msg_encrypt, but operate on an appdata directly.
send_appdata_encrypt(&mut self, payload: &[u8], limit: Limit) -> usize563 fn send_appdata_encrypt(&mut self,
564 payload: &[u8],
565 limit: Limit) -> usize {
566 // Here, the limit on sendable_tls applies to encrypted data,
567 // but we're respecting it for plaintext data -- so we'll
568 // be out by whatever the cipher+record overhead is. That's a
569 // constant and predictable amount, so it's not a terrible issue.
570 let len = match limit {
571 Limit::Yes => self.sendable_tls.apply_limit(payload.len()),
572 Limit::No => payload.len()
573 };
574
575 let mut plain_messages = VecDeque::new();
576 self.message_fragmenter.fragment_borrow(ContentType::ApplicationData,
577 ProtocolVersion::TLSv1_2,
578 &payload[..len],
579 &mut plain_messages);
580
581 for m in plain_messages {
582 self.send_single_fragment(m);
583 }
584
585 len
586 }
587
send_single_fragment(&mut self, m: BorrowMessage)588 fn send_single_fragment(&mut self, m: BorrowMessage) {
589 // Close connection once we start to run out of
590 // sequence space.
591 if self.record_layer.wants_close_before_encrypt() {
592 self.send_close_notify();
593 }
594
595 // Refuse to wrap counter at all costs. This
596 // is basically untestable unfortunately.
597 if self.record_layer.encrypt_exhausted() {
598 return;
599 }
600
601 let em = self.record_layer.encrypt_outgoing(m);
602 self.queue_tls_message(em);
603 }
604
605 /// Are we done? ie, have we processed all received messages,
606 /// and received a close_notify to indicate that no new messages
607 /// will arrive?
connection_at_eof(&self) -> bool608 pub fn connection_at_eof(&self) -> bool {
609 self.peer_eof && !self.message_deframer.has_pending()
610 }
611
612 /// Read TLS content from `rd`. This method does internal
613 /// buffering, so `rd` can supply TLS messages in arbitrary-
614 /// sized chunks (like a socket or pipe might).
read_tls(&mut self, rd: &mut dyn Read) -> io::Result<usize>615 pub fn read_tls(&mut self, rd: &mut dyn Read) -> io::Result<usize> {
616 self.message_deframer.read(rd)
617 }
618
write_tls(&mut self, wr: &mut dyn Write) -> io::Result<usize>619 pub fn write_tls(&mut self, wr: &mut dyn Write) -> io::Result<usize> {
620 self.sendable_tls.write_to(wr)
621 }
622
623 /// Send plaintext application data, fragmenting and
624 /// encrypting it as it goes out.
625 ///
626 /// If internal buffers are too small, this function will not accept
627 /// all the data.
send_some_plaintext(&mut self, data: &[u8]) -> io::Result<usize>628 pub fn send_some_plaintext(&mut self, data: &[u8]) -> io::Result<usize> {
629 self.send_plain(data, Limit::Yes)
630 }
631
send_early_plaintext(&mut self, data: &[u8]) -> io::Result<usize>632 pub fn send_early_plaintext(&mut self, data: &[u8]) -> io::Result<usize> {
633 debug_assert!(self.early_traffic);
634 debug_assert!(self.record_layer.is_encrypting());
635
636 if data.is_empty() {
637 // Don't send empty fragments.
638 return Ok(0);
639 }
640
641 Ok(self.send_appdata_encrypt(data, Limit::Yes))
642 }
643
send_plain(&mut self, data: &[u8], limit: Limit) -> io::Result<usize>644 fn send_plain(&mut self, data: &[u8], limit: Limit) -> io::Result<usize> {
645 if !self.traffic {
646 // If we haven't completed handshaking, buffer
647 // plaintext to send once we do.
648 let len = match limit {
649 Limit::Yes => self.sendable_plaintext.append_limited_copy(data),
650 Limit::No => self.sendable_plaintext.append(data.to_vec())
651 };
652 return Ok(len);
653 }
654
655 debug_assert!(self.record_layer.is_encrypting());
656
657 if data.is_empty() {
658 // Don't send empty fragments.
659 return Ok(0);
660 }
661
662 Ok(self.send_appdata_encrypt(data, limit))
663 }
664
start_traffic(&mut self)665 pub fn start_traffic(&mut self) {
666 self.traffic = true;
667 self.flush_plaintext();
668 }
669
670 /// Send any buffered plaintext. Plaintext is buffered if
671 /// written during handshake.
flush_plaintext(&mut self)672 pub fn flush_plaintext(&mut self) {
673 if !self.traffic {
674 return;
675 }
676
677 while !self.sendable_plaintext.is_empty() {
678 let buf = self.sendable_plaintext.take_one();
679 self.send_plain(&buf, Limit::No)
680 .unwrap();
681 }
682 }
683
684 // Put m into sendable_tls for writing.
queue_tls_message(&mut self, m: Message)685 fn queue_tls_message(&mut self, m: Message) {
686 self.sendable_tls.append(m.get_encoding());
687 }
688
689 /// Send a raw TLS message, fragmenting it if needed.
send_msg(&mut self, m: Message, must_encrypt: bool)690 pub fn send_msg(&mut self, m: Message, must_encrypt: bool) {
691 #[cfg(feature = "quic")]
692 {
693 if let Protocol::Quic = self.protocol {
694 if let MessagePayload::Alert(alert) = m.payload {
695 self.quic.alert = Some(alert.description);
696 } else {
697 debug_assert!(if let MessagePayload::Handshake(_) = m.payload { true } else { false },
698 "QUIC uses TLS for the cryptographic handshake only");
699 let mut bytes = Vec::new();
700 m.payload.encode(&mut bytes);
701 self.quic.hs_queue.push_back((must_encrypt, bytes));
702 }
703 return;
704 }
705 }
706 if !must_encrypt {
707 let mut to_send = VecDeque::new();
708 self.message_fragmenter.fragment(m, &mut to_send);
709 for mm in to_send {
710 self.queue_tls_message(mm);
711 }
712 } else {
713 self.send_msg_encrypt(m);
714 }
715 }
716
take_received_plaintext(&mut self, bytes: Payload)717 pub fn take_received_plaintext(&mut self, bytes: Payload) {
718 self.received_plaintext.append(bytes.0);
719 }
720
read(&mut self, buf: &mut [u8]) -> io::Result<usize>721 pub fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
722 let len = self.received_plaintext.read(buf)?;
723
724 if len == 0 && self.connection_at_eof() && self.received_plaintext.is_empty() {
725 return Err(io::Error::new(io::ErrorKind::ConnectionAborted,
726 "CloseNotify alert received"));
727 }
728
729 Ok(len)
730 }
731
start_encryption_tls12(&mut self, secrets: &SessionSecrets)732 pub fn start_encryption_tls12(&mut self, secrets: &SessionSecrets) {
733 let (dec, enc) = cipher::new_tls12(self.get_suite_assert(), secrets);
734 self.record_layer.prepare_message_encrypter(enc);
735 self.record_layer.prepare_message_decrypter(dec);
736 }
737
send_warning_alert(&mut self, desc: AlertDescription)738 pub fn send_warning_alert(&mut self, desc: AlertDescription) {
739 warn!("Sending warning alert {:?}", desc);
740 self.send_warning_alert_no_log(desc);
741 }
742
send_fatal_alert(&mut self, desc: AlertDescription)743 pub fn send_fatal_alert(&mut self, desc: AlertDescription) {
744 warn!("Sending fatal alert {:?}", desc);
745 debug_assert!(!self.sent_fatal_alert);
746 let m = Message::build_alert(AlertLevel::Fatal, desc);
747 self.send_msg(m, self.record_layer.is_encrypting());
748 self.sent_fatal_alert = true;
749 }
750
send_close_notify(&mut self)751 pub fn send_close_notify(&mut self) {
752 debug!("Sending warning alert {:?}", AlertDescription::CloseNotify);
753 self.send_warning_alert_no_log(AlertDescription::CloseNotify);
754 }
755
send_warning_alert_no_log(&mut self, desc: AlertDescription)756 fn send_warning_alert_no_log(&mut self, desc: AlertDescription) {
757 let m = Message::build_alert(AlertLevel::Warning, desc);
758 self.send_msg(m, self.record_layer.is_encrypting());
759 }
760
is_quic(&self) -> bool761 pub fn is_quic(&self) -> bool {
762 #[cfg(feature = "quic")]
763 {
764 self.protocol == Protocol::Quic
765 }
766 #[cfg(not(feature = "quic"))]
767 false
768 }
769 }
770
771
772 #[cfg(feature = "quic")]
773 pub(crate) struct Quic {
774 /// QUIC transport parameters received from the peer during the handshake
775 pub params: Option<Vec<u8>>,
776 pub alert: Option<AlertDescription>,
777 pub hs_queue: VecDeque<(bool, Vec<u8>)>,
778 pub early_secret: Option<ring::hkdf::Prk>,
779 pub hs_secrets: Option<quic::Secrets>,
780 pub traffic_secrets: Option<quic::Secrets>,
781 /// Whether keys derived from traffic_secrets have been passed to the QUIC implementation
782 pub returned_traffic_keys: bool,
783 }
784
785 #[cfg(feature = "quic")]
786 impl Quic {
new() -> Self787 pub fn new() -> Self {
788 Self {
789 params: None,
790 alert: None,
791 hs_queue: VecDeque::new(),
792 early_secret: None,
793 hs_secrets: None,
794 traffic_secrets: None,
795 returned_traffic_keys: false,
796 }
797 }
798 }
799