1 use crate::session::{Session, SessionCommon};
2 use crate::keylog::{KeyLog, NoKeyLog};
3 use crate::suites::{SupportedCipherSuite, ALL_CIPHERSUITES};
4 use crate::msgs::enums::ContentType;
5 use crate::msgs::enums::SignatureScheme;
6 use crate::msgs::enums::{AlertDescription, HandshakeType, ProtocolVersion};
7 use crate::msgs::handshake::ServerExtension;
8 use crate::msgs::message::Message;
9 use crate::error::TLSError;
10 use crate::sign;
11 use crate::verify;
12 use crate::key;
13 use crate::vecbuf::WriteV;
14 #[cfg(feature = "logging")]
15 use crate::log::trace;
16 
17 use webpki;
18 
19 use std::sync::Arc;
20 use std::io;
21 use std::fmt;
22 
23 #[macro_use]
24 mod hs;
25 mod tls12;
26 mod tls13;
27 mod common;
28 pub mod handy;
29 
30 /// A trait for the ability to store server session data.
31 ///
32 /// The keys and values are opaque.
33 ///
34 /// Both the keys and values should be treated as
35 /// **highly sensitive data**, containing enough key material
36 /// to break all security of the corresponding sessions.
37 ///
38 /// Implementations can be lossy (in other words, forgetting
39 /// key/value pairs) without any negative security consequences.
40 ///
41 /// However, note that `take` **must** reliably delete a returned
42 /// value.  If it does not, there may be security consequences.
43 ///
44 /// `put` and `take` are mutating operations; this isn't expressed
45 /// in the type system to allow implementations freedom in
46 /// how to achieve interior mutability.  `Mutex` is a common
47 /// choice.
48 pub trait StoresServerSessions : Send + Sync {
49     /// Store session secrets encoded in `value` against `key`,
50     /// overwrites any existing value against `key`.  Returns `true`
51     /// if the value was stored.
put(&self, key: Vec<u8>, value: Vec<u8>) -> bool52     fn put(&self, key: Vec<u8>, value: Vec<u8>) -> bool;
53 
54     /// Find a value with the given `key`.  Return it, or None
55     /// if it doesn't exist.
get(&self, key: &[u8]) -> Option<Vec<u8>>56     fn get(&self, key: &[u8]) -> Option<Vec<u8>>;
57 
58     /// Find a value with the given `key`.  Return it and delete it;
59     /// or None if it doesn't exist.
take(&self, key: &[u8]) -> Option<Vec<u8>>60     fn take(&self, key: &[u8]) -> Option<Vec<u8>>;
61 }
62 
63 /// A trait for the ability to encrypt and decrypt tickets.
64 pub trait ProducesTickets : Send + Sync {
65     /// Returns true if this implementation will encrypt/decrypt
66     /// tickets.  Should return false if this is a dummy
67     /// implementation: the server will not send the SessionTicket
68     /// extension and will not call the other functions.
enabled(&self) -> bool69     fn enabled(&self) -> bool;
70 
71     /// Returns the lifetime in seconds of tickets produced now.
72     /// The lifetime is provided as a hint to clients that the
73     /// ticket will not be useful after the given time.
74     ///
75     /// This lifetime must be implemented by key rolling and
76     /// erasure, *not* by storing a lifetime in the ticket.
77     ///
78     /// The objective is to limit damage to forward secrecy caused
79     /// by tickets, not just limiting their lifetime.
get_lifetime(&self) -> u3280     fn get_lifetime(&self) -> u32;
81 
82     /// Encrypt and authenticate `plain`, returning the resulting
83     /// ticket.  Return None if `plain` cannot be encrypted for
84     /// some reason: an empty ticket will be sent and the connection
85     /// will continue.
encrypt(&self, plain: &[u8]) -> Option<Vec<u8>>86     fn encrypt(&self, plain: &[u8]) -> Option<Vec<u8>>;
87 
88     /// Decrypt `cipher`, validating its authenticity protection
89     /// and recovering the plaintext.  `cipher` is fully attacker
90     /// controlled, so this decryption must be side-channel free,
91     /// panic-proof, and otherwise bullet-proof.  If the decryption
92     /// fails, return None.
decrypt(&self, cipher: &[u8]) -> Option<Vec<u8>>93     fn decrypt(&self, cipher: &[u8]) -> Option<Vec<u8>>;
94 }
95 
96 /// How to choose a certificate chain and signing key for use
97 /// in server authentication.
98 pub trait ResolvesServerCert : Send + Sync {
99     /// Choose a certificate chain and matching key given simplified
100     /// ClientHello information.
101     ///
102     /// Return `None` to abort the handshake.
resolve(&self, client_hello: ClientHello) -> Option<sign::CertifiedKey>103     fn resolve(&self, client_hello: ClientHello) -> Option<sign::CertifiedKey>;
104 }
105 
106 /// A struct representing the received Client Hello
107 pub struct ClientHello<'a> {
108     server_name: Option<webpki::DNSNameRef<'a>>,
109     sigschemes: &'a [SignatureScheme],
110     alpn: Option<&'a[&'a[u8]]>,
111 }
112 
113 impl<'a> ClientHello<'a> {
114     /// Creates a new ClientHello
new(server_name: Option<webpki::DNSNameRef<'a>>, sigschemes: &'a [SignatureScheme], alpn: Option<&'a[&'a[u8]]>)->Self115     fn new(server_name: Option<webpki::DNSNameRef<'a>>, sigschemes:  &'a [SignatureScheme],
116     alpn: Option<&'a[&'a[u8]]>)->Self {
117         ClientHello {server_name, sigschemes, alpn}
118     }
119 
120     /// Get the server name indicator.
121     ///
122     /// Returns `None` if the client did not supply a SNI.
server_name(&self) -> Option<webpki::DNSNameRef>123     pub fn server_name(&self) -> Option<webpki::DNSNameRef> {
124         self.server_name
125     }
126 
127     /// Get the compatible signature schemes.
128     ///
129     /// Returns standard-specified default if the client omitted this extension.
sigschemes(&self) -> &[SignatureScheme]130     pub fn sigschemes(&self) -> &[SignatureScheme] {
131         self.sigschemes
132     }
133 
134     /// Get the alpn.
135     ///
136     /// Returns `None` if the client did not include an ALPN extension
alpn(&self) -> Option<&'a[&'a[u8]]>137     pub fn alpn(&self) -> Option<&'a[&'a[u8]]> {
138         self.alpn
139     }
140 }
141 
142 /// Common configuration for a set of server sessions.
143 ///
144 /// Making one of these can be expensive, and should be
145 /// once per process rather than once per connection.
146 #[derive(Clone)]
147 pub struct ServerConfig {
148     /// List of ciphersuites, in preference order.
149     pub ciphersuites: Vec<&'static SupportedCipherSuite>,
150 
151     /// Ignore the client's ciphersuite order. Instead,
152     /// choose the top ciphersuite in the server list
153     /// which is supported by the client.
154     pub ignore_client_order: bool,
155 
156     /// Our MTU.  If None, we don't limit TLS message sizes.
157     pub mtu: Option<usize>,
158 
159     /// How to store client sessions.
160     pub session_storage: Arc<dyn StoresServerSessions + Send + Sync>,
161 
162     /// How to produce tickets.
163     pub ticketer: Arc<dyn ProducesTickets>,
164 
165     /// How to choose a server cert and key.
166     pub cert_resolver: Arc<dyn ResolvesServerCert>,
167 
168     /// Protocol names we support, most preferred first.
169     /// If empty we don't do ALPN at all.
170     pub alpn_protocols: Vec<Vec<u8>>,
171 
172     /// Supported protocol versions, in no particular order.
173     /// The default is all supported versions.
174     pub versions: Vec<ProtocolVersion>,
175 
176     /// How to verify client certificates.
177     verifier: Arc<dyn verify::ClientCertVerifier>,
178 
179     /// How to output key material for debugging.  The default
180     /// does nothing.
181     pub key_log: Arc<dyn KeyLog>,
182 
183     /// Amount of early data to accept; 0 to disable.
184     #[cfg(feature = "quic")]    // TLS support unimplemented
185     #[doc(hidden)]
186     pub max_early_data_size: u32,
187 }
188 
189 impl ServerConfig {
190     /// Make a `ServerConfig` with a default set of ciphersuites,
191     /// no keys/certificates, and no ALPN protocols.  Session resumption
192     /// is enabled by storing up to 256 recent sessions in memory. Tickets are
193     /// disabled.
194     ///
195     /// Publicly-available web servers on the internet generally don't do client
196     /// authentication; for this use case, `client_cert_verifier` should be a
197     /// `NoClientAuth`. Otherwise, use `AllowAnyAuthenticatedClient` or another
198     /// implementation to enforce client authentication.
199     ///
200     /// We don't provide a default for `client_cert_verifier` because the safest
201     /// default, requiring client authentication, requires additional
202     /// configuration that we cannot provide reasonable defaults for.
new(client_cert_verifier: Arc<dyn verify::ClientCertVerifier>) -> ServerConfig203     pub fn new(client_cert_verifier: Arc<dyn verify::ClientCertVerifier>) -> ServerConfig {
204         ServerConfig {
205             ciphersuites: ALL_CIPHERSUITES.to_vec(),
206             ignore_client_order: false,
207             mtu: None,
208             session_storage: handy::ServerSessionMemoryCache::new(256),
209             ticketer: Arc::new(handy::NeverProducesTickets {}),
210             alpn_protocols: Vec::new(),
211             cert_resolver: Arc::new(handy::FailResolveChain {}),
212             versions: vec![ ProtocolVersion::TLSv1_3, ProtocolVersion::TLSv1_2 ],
213             verifier: client_cert_verifier,
214             key_log: Arc::new(NoKeyLog {}),
215             #[cfg(feature = "quic")]
216             max_early_data_size: 0,
217         }
218     }
219 
220     #[doc(hidden)]
221     /// We support a given TLS version if it's quoted in the configured
222     /// versions *and* at least one ciphersuite for this version is
223     /// also configured.
supports_version(&self, v: ProtocolVersion) -> bool224     pub fn supports_version(&self, v: ProtocolVersion) -> bool {
225         self.versions.contains(&v) && self.ciphersuites.iter().any(|cs| cs.usable_for_version(v))
226     }
227 
228     #[doc(hidden)]
get_verifier(&self) -> &dyn verify::ClientCertVerifier229     pub fn get_verifier(&self) -> &dyn verify::ClientCertVerifier {
230         self.verifier.as_ref()
231     }
232 
233     /// Sets the session persistence layer to `persist`.
set_persistence(&mut self, persist: Arc<dyn StoresServerSessions + Send + Sync>)234     pub fn set_persistence(&mut self, persist: Arc<dyn StoresServerSessions + Send + Sync>) {
235         self.session_storage = persist;
236     }
237 
238     /// Sets a single certificate chain and matching private key.  This
239     /// certificate and key is used for all subsequent connections,
240     /// irrespective of things like SNI hostname.
241     ///
242     /// Note that the end-entity certificate must have the
243     /// [Subject Alternative Name](https://tools.ietf.org/html/rfc6125#section-4.1)
244     /// extension to describe, e.g., the valid DNS name. The `commonName` field is
245     /// disregarded.
246     ///
247     /// `cert_chain` is a vector of DER-encoded certificates.
248     /// `key_der` is a DER-encoded RSA or ECDSA private key.
249     ///
250     /// This function fails if `key_der` is invalid.
set_single_cert(&mut self, cert_chain: Vec<key::Certificate>, key_der: key::PrivateKey) -> Result<(), TLSError>251     pub fn set_single_cert(&mut self,
252                            cert_chain: Vec<key::Certificate>,
253                            key_der: key::PrivateKey) -> Result<(), TLSError> {
254         let resolver = handy::AlwaysResolvesChain::new(cert_chain, &key_der)?;
255         self.cert_resolver = Arc::new(resolver);
256         Ok(())
257     }
258 
259     /// Sets a single certificate chain, matching private key and OCSP
260     /// response.  This certificate and key is used for all subsequent
261     /// connections, irrespective of things like SNI hostname.
262     ///
263     /// `cert_chain` is a vector of DER-encoded certificates.
264     /// `key_der` is a DER-encoded RSA or ECDSA private key.
265     /// `ocsp` is a DER-encoded OCSP response.  Ignored if zero length.
266     /// `scts` is an `SignedCertificateTimestampList` encoding (see RFC6962)
267     /// and is ignored if empty.
268     ///
269     /// This function fails if `key_der` is invalid.
set_single_cert_with_ocsp_and_sct(&mut self, cert_chain: Vec<key::Certificate>, key_der: key::PrivateKey, ocsp: Vec<u8>, scts: Vec<u8>) -> Result<(), TLSError>270     pub fn set_single_cert_with_ocsp_and_sct(&mut self,
271                                              cert_chain: Vec<key::Certificate>,
272                                              key_der: key::PrivateKey,
273                                              ocsp: Vec<u8>,
274                                              scts: Vec<u8>) -> Result<(), TLSError> {
275         let resolver = handy::AlwaysResolvesChain::new_with_extras(cert_chain,
276                                                                    &key_der,
277                                                                    ocsp,
278                                                                    scts)?;
279         self.cert_resolver = Arc::new(resolver);
280         Ok(())
281     }
282 
283     /// Set the ALPN protocol list to the given protocol names.
284     /// Overwrites any existing configured protocols.
285     ///
286     /// The first element in the `protocols` list is the most
287     /// preferred, the last is the least preferred.
set_protocols(&mut self, protocols: &[Vec<u8>])288     pub fn set_protocols(&mut self, protocols: &[Vec<u8>]) {
289         self.alpn_protocols.clear();
290         self.alpn_protocols.extend_from_slice(protocols);
291     }
292 
293     /// Overrides the default `ClientCertVerifier` with something else.
set_client_certificate_verifier(&mut self, verifier: Arc<dyn verify::ClientCertVerifier>)294     pub fn set_client_certificate_verifier(&mut self, verifier: Arc<dyn verify::ClientCertVerifier>) {
295         self.verifier = verifier;
296     }
297 }
298 
299 pub struct ServerSessionImpl {
300     pub config: Arc<ServerConfig>,
301     pub common: SessionCommon,
302     sni: Option<webpki::DNSName>,
303     pub alpn_protocol: Option<Vec<u8>>,
304     pub quic_params: Option<Vec<u8>>,
305     pub received_resumption_data: Option<Vec<u8>>,
306     pub resumption_data: Vec<u8>,
307     pub error: Option<TLSError>,
308     pub state: Option<Box<dyn hs::State + Send + Sync>>,
309     pub client_cert_chain: Option<Vec<key::Certificate>>,
310     /// Whether to reject early data even if it would otherwise be accepted
311     pub reject_early_data: bool,
312 }
313 
314 impl fmt::Debug for ServerSessionImpl {
fmt(&self, f: &mut fmt::Formatter) -> fmt::Result315     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
316         f.debug_struct("ServerSessionImpl").finish()
317     }
318 }
319 
320 impl ServerSessionImpl {
new(server_config: &Arc<ServerConfig>, extra_exts: Vec<ServerExtension>) -> ServerSessionImpl321     pub fn new(server_config: &Arc<ServerConfig>, extra_exts: Vec<ServerExtension>)
322                -> ServerSessionImpl {
323         ServerSessionImpl {
324             config: server_config.clone(),
325             common: SessionCommon::new(server_config.mtu, false),
326             sni: None,
327             alpn_protocol: None,
328             quic_params: None,
329             received_resumption_data: None,
330             resumption_data: Vec::new(),
331             error: None,
332             state: Some(Box::new(hs::ExpectClientHello::new(server_config, extra_exts))),
333             client_cert_chain: None,
334             reject_early_data: false,
335         }
336     }
337 
wants_read(&self) -> bool338     pub fn wants_read(&self) -> bool {
339         // We want to read more data all the time, except when we
340         // have unprocessed plaintext.  This provides back-pressure
341         // to the TCP buffers.
342         //
343         // This also covers the handshake case, because we don't have
344         // readable plaintext before handshake has completed.
345         !self.common.has_readable_plaintext()
346     }
347 
wants_write(&self) -> bool348     pub fn wants_write(&self) -> bool {
349         !self.common.sendable_tls.is_empty()
350     }
351 
is_handshaking(&self) -> bool352     pub fn is_handshaking(&self) -> bool {
353         !self.common.traffic
354     }
355 
set_buffer_limit(&mut self, len: usize)356     pub fn set_buffer_limit(&mut self, len: usize) {
357         self.common.set_buffer_limit(len)
358     }
359 
process_msg(&mut self, mut msg: Message) -> Result<(), TLSError>360     pub fn process_msg(&mut self, mut msg: Message) -> Result<(), TLSError> {
361         // TLS1.3: drop CCS at any time during handshaking
362         if self.common.is_tls13()
363             && msg.is_content_type(ContentType::ChangeCipherSpec)
364             && self.is_handshaking() {
365             trace!("Dropping CCS");
366             return Ok(());
367         }
368 
369         // Decrypt if demanded by current state.
370         if self.common.record_layer.is_decrypting() {
371             let dm = self.common.decrypt_incoming(msg)?;
372             msg = dm;
373         }
374 
375         // For handshake messages, we need to join them before parsing
376         // and processing.
377         if self.common.handshake_joiner.want_message(&msg) {
378             self.common.handshake_joiner.take_message(msg)
379                 .ok_or_else(|| {
380                             self.common.send_fatal_alert(AlertDescription::DecodeError);
381                             TLSError::CorruptMessagePayload(ContentType::Handshake)
382                             })?;
383             return self.process_new_handshake_messages();
384         }
385 
386         // Now we can fully parse the message payload.
387         msg.decode_payload();
388 
389         if msg.is_content_type(ContentType::Alert) {
390             return self.common.process_alert(msg);
391         }
392 
393         self.process_main_protocol(msg)
394     }
395 
process_new_handshake_messages(&mut self) -> Result<(), TLSError>396     pub fn process_new_handshake_messages(&mut self) -> Result<(), TLSError> {
397         while let Some(msg) = self.common.handshake_joiner.frames.pop_front() {
398             self.process_main_protocol(msg)?;
399         }
400 
401         Ok(())
402     }
403 
queue_unexpected_alert(&mut self)404     fn queue_unexpected_alert(&mut self) {
405         self.common.send_fatal_alert(AlertDescription::UnexpectedMessage);
406     }
407 
process_main_protocol(&mut self, msg: Message) -> Result<(), TLSError>408     pub fn process_main_protocol(&mut self, msg: Message) -> Result<(), TLSError> {
409         if self.common.traffic && !self.common.is_tls13() &&
410            msg.is_handshake_type(HandshakeType::ClientHello) {
411             self.common.send_warning_alert(AlertDescription::NoRenegotiation);
412             return Ok(());
413         }
414 
415         let st = self.state.take().unwrap();
416         st.check_message(&msg)
417             .map_err(|err| { self.queue_unexpected_alert(); err })?;
418 
419         self.state = Some(st.handle(self, msg)?);
420 
421         Ok(())
422     }
423 
process_new_packets(&mut self) -> Result<(), TLSError>424     pub fn process_new_packets(&mut self) -> Result<(), TLSError> {
425         if let Some(ref err) = self.error {
426             return Err(err.clone());
427         }
428 
429         if self.common.message_deframer.desynced {
430             return Err(TLSError::CorruptMessage);
431         }
432 
433         while let Some(msg) = self.common.message_deframer.frames.pop_front() {
434             match self.process_msg(msg) {
435                 Ok(_) => {}
436                 Err(err) => {
437                     self.error = Some(err.clone());
438                     return Err(err);
439                 }
440             }
441 
442         }
443 
444         Ok(())
445     }
446 
get_peer_certificates(&self) -> Option<Vec<key::Certificate>>447     pub fn get_peer_certificates(&self) -> Option<Vec<key::Certificate>> {
448         let certs = self.client_cert_chain.as_ref()?;
449         let mut r = Vec::new();
450 
451         for cert in certs {
452             r.push(cert.clone());
453         }
454 
455         Some(r)
456     }
457 
get_alpn_protocol(&self) -> Option<&[u8]>458     pub fn get_alpn_protocol(&self) -> Option<&[u8]> {
459         self.alpn_protocol.as_ref().map(AsRef::as_ref)
460     }
461 
get_protocol_version(&self) -> Option<ProtocolVersion>462     pub fn get_protocol_version(&self) -> Option<ProtocolVersion> {
463         self.common.negotiated_version
464     }
465 
get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite>466     pub fn get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite> {
467         self.common.get_suite()
468     }
469 
get_sni(&self)-> Option<&webpki::DNSName>470     pub fn get_sni(&self)-> Option<&webpki::DNSName> {
471         self.sni.as_ref()
472     }
473 
set_sni(&mut self, value: webpki::DNSName)474     pub fn set_sni(&mut self, value: webpki::DNSName) {
475         // The SNI hostname is immutable once set.
476         assert!(self.sni.is_none());
477         self.sni = Some(value)
478     }
479 
export_keying_material(&self, output: &mut [u8], label: &[u8], context: Option<&[u8]>) -> Result<(), TLSError>480     fn export_keying_material(&self,
481                               output: &mut [u8],
482                               label: &[u8],
483                               context: Option<&[u8]>) -> Result<(), TLSError> {
484         self.state
485             .as_ref()
486             .ok_or_else(|| TLSError::HandshakeNotComplete)
487             .and_then(|st| st.export_keying_material(output, label, context))
488     }
489 
send_some_plaintext(&mut self, buf: &[u8]) -> io::Result<usize>490     fn send_some_plaintext(&mut self, buf: &[u8]) -> io::Result<usize> {
491         let mut st = self.state.take();
492         st.as_mut()
493           .map(|st| st.perhaps_write_key_update(self));
494         self.state = st;
495         self.common.send_some_plaintext(buf)
496     }
497 }
498 
499 /// This represents a single TLS server session.
500 ///
501 /// Send TLS-protected data to the peer using the `io::Write` trait implementation.
502 /// Read data from the peer using the `io::Read` trait implementation.
503 #[derive(Debug)]
504 pub struct ServerSession {
505     // We use the pimpl idiom to hide unimportant details.
506     pub(crate) imp: ServerSessionImpl,
507 }
508 
509 impl ServerSession {
510     /// Make a new ServerSession.  `config` controls how
511     /// we behave in the TLS protocol.
new(config: &Arc<ServerConfig>) -> ServerSession512     pub fn new(config: &Arc<ServerConfig>) -> ServerSession {
513         ServerSession { imp: ServerSessionImpl::new(config, vec![]) }
514     }
515 
516     /// Retrieves the SNI hostname, if any, used to select the certificate and
517     /// private key.
518     ///
519     /// This returns `None` until some time after the client's SNI extension
520     /// value is processed during the handshake. It will never be `None` when
521     /// the connection is ready to send or process application data, unless the
522     /// client does not support SNI.
523     ///
524     /// This is useful for application protocols that need to enforce that the
525     /// SNI hostname matches an application layer protocol hostname. For
526     /// example, HTTP/1.1 servers commonly expect the `Host:` header field of
527     /// every request on a connection to match the hostname in the SNI extension
528     /// when the client provides the SNI extension.
529     ///
530     /// The SNI hostname is also used to match sessions during session
531     /// resumption.
get_sni_hostname(&self)-> Option<&str>532     pub fn get_sni_hostname(&self)-> Option<&str> {
533         self.imp.get_sni().map(|s| s.as_ref().into())
534     }
535 
536     /// Application-controlled portion of the resumption ticket supplied by the client, if any.
537     ///
538     /// Recovered from the prior session's `set_resumption_data`. Integrity is guaranteed by rustls.
539     ///
540     /// Returns `Some` iff a valid resumption ticket has been received from the client.
received_resumption_data(&self) -> Option<&[u8]>541     pub fn received_resumption_data(&self) -> Option<&[u8]> {
542         self.imp.received_resumption_data.as_ref().map(|x| &x[..])
543     }
544 
545     /// Set the resumption data to embed in future resumption tickets supplied to the client.
546     ///
547     /// Defaults to the empty byte string. Must be less than 2^15 bytes to allow room for other
548     /// data. Should be called while `is_handshaking` returns true to ensure all transmitted
549     /// resumption tickets are affected.
550     ///
551     /// Integrity will be assured by rustls, but the data will be visible to the client. If secrecy
552     /// from the client is desired, encrypt the data separately.
set_resumption_data(&mut self, data: &[u8])553     pub fn set_resumption_data(&mut self, data: &[u8]) {
554         assert!(data.len() < 2usize.pow(15));
555         self.imp.resumption_data = data.into();
556     }
557 
558     /// Explicitly discard early data, notifying the client
559     ///
560     /// Useful if invariants encoded in `received_resumption_data()` cannot be respected.
561     ///
562     /// Must be called while `is_handshaking` is true.
reject_early_data(&mut self)563     pub fn reject_early_data(&mut self) {
564         assert!(self.is_handshaking(), "cannot retroactively reject early data");
565         self.imp.reject_early_data = true;
566     }
567 }
568 
569 impl Session for ServerSession {
read_tls(&mut self, rd: &mut dyn io::Read) -> io::Result<usize>570     fn read_tls(&mut self, rd: &mut dyn io::Read) -> io::Result<usize> {
571         self.imp.common.read_tls(rd)
572     }
573 
574     /// Writes TLS messages to `wr`.
write_tls(&mut self, wr: &mut dyn io::Write) -> io::Result<usize>575     fn write_tls(&mut self, wr: &mut dyn io::Write) -> io::Result<usize> {
576         self.imp.common.write_tls(wr)
577     }
578 
writev_tls(&mut self, wr: &mut dyn WriteV) -> io::Result<usize>579     fn writev_tls(&mut self, wr: &mut dyn WriteV) -> io::Result<usize> {
580         self.imp.common.writev_tls(wr)
581     }
582 
process_new_packets(&mut self) -> Result<(), TLSError>583     fn process_new_packets(&mut self) -> Result<(), TLSError> {
584         self.imp.process_new_packets()
585     }
586 
wants_read(&self) -> bool587     fn wants_read(&self) -> bool {
588         self.imp.wants_read()
589     }
590 
wants_write(&self) -> bool591     fn wants_write(&self) -> bool {
592         self.imp.wants_write()
593     }
594 
is_handshaking(&self) -> bool595     fn is_handshaking(&self) -> bool {
596         self.imp.is_handshaking()
597     }
598 
set_buffer_limit(&mut self, len: usize)599     fn set_buffer_limit(&mut self, len: usize) {
600         self.imp.set_buffer_limit(len)
601     }
602 
send_close_notify(&mut self)603     fn send_close_notify(&mut self) {
604         self.imp.common.send_close_notify()
605     }
606 
get_peer_certificates(&self) -> Option<Vec<key::Certificate>>607     fn get_peer_certificates(&self) -> Option<Vec<key::Certificate>> {
608         self.imp.get_peer_certificates()
609     }
610 
get_alpn_protocol(&self) -> Option<&[u8]>611     fn get_alpn_protocol(&self) -> Option<&[u8]> {
612         self.imp.get_alpn_protocol()
613     }
614 
get_protocol_version(&self) -> Option<ProtocolVersion>615     fn get_protocol_version(&self) -> Option<ProtocolVersion> {
616         self.imp.get_protocol_version()
617     }
618 
export_keying_material(&self, output: &mut [u8], label: &[u8], context: Option<&[u8]>) -> Result<(), TLSError>619     fn export_keying_material(&self,
620                               output: &mut [u8],
621                               label: &[u8],
622                               context: Option<&[u8]>) -> Result<(), TLSError> {
623         self.imp.export_keying_material(output, label, context)
624     }
625 
get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite>626     fn get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite> {
627         self.imp.get_negotiated_ciphersuite()
628     }
629 }
630 
631 impl io::Read for ServerSession {
632     /// Obtain plaintext data received from the peer over
633     /// this TLS connection.
read(&mut self, buf: &mut [u8]) -> io::Result<usize>634     fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
635         self.imp.common.read(buf)
636     }
637 }
638 
639 impl io::Write for ServerSession {
640     /// Send the plaintext `buf` to the peer, encrypting
641     /// and authenticating it.  Once this function succeeds
642     /// you should call `write_tls` which will output the
643     /// corresponding TLS records.
644     ///
645     /// This function buffers plaintext sent before the
646     /// TLS handshake completes, and sends it as soon
647     /// as it can.  This buffer is of *unlimited size* so
648     /// writing much data before it can be sent will
649     /// cause excess memory usage.
write(&mut self, buf: &[u8]) -> io::Result<usize>650     fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
651         self.imp.send_some_plaintext(buf)
652     }
653 
flush(&mut self) -> io::Result<()>654     fn flush(&mut self) -> io::Result<()> {
655         self.imp.common.flush_plaintext();
656         Ok(())
657     }
658 }
659