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