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