use session::{Session, SessionCommon};
use suites::{SupportedCipherSuite, ALL_CIPHERSUITES};
use msgs::enums::{ContentType, SignatureScheme};
use msgs::enums::{AlertDescription, HandshakeType, ProtocolVersion};
use msgs::handshake::SessionID;
use msgs::message::Message;
use error::TLSError;
use sign;
use verify;
use key;
use webpki;
use std::sync::Arc;
use std::io;
use std::fmt;
mod hs;
mod common;
pub mod handy;
pub trait StoresServerSessions : Send + Sync {
fn generate(&self) -> SessionID;
fn put(&self, id: &SessionID, value: Vec<u8>) -> bool;
fn get(&self, id: &SessionID) -> Option<Vec<u8>>;
fn del(&self, id: &SessionID) -> bool;
}
pub trait ProducesTickets : Send + Sync {
fn enabled(&self) -> bool;
fn get_lifetime(&self) -> u32;
fn encrypt(&self, plain: &[u8]) -> Option<Vec<u8>>;
fn decrypt(&self, cipher: &[u8]) -> Option<Vec<u8>>;
}
pub trait ResolvesServerCert : Send + Sync {
fn resolve(&self,
server_name: Option<webpki::DNSNameRef>,
sigschemes: &[SignatureScheme])
-> Option<sign::CertifiedKey>;
}
#[derive(Clone)]
pub struct ServerConfig {
pub ciphersuites: Vec<&'static SupportedCipherSuite>,
pub ignore_client_order: bool,
pub mtu: Option<usize>,
pub session_storage: Arc<StoresServerSessions + Send + Sync>,
pub ticketer: Arc<ProducesTickets>,
pub cert_resolver: Arc<ResolvesServerCert>,
pub alpn_protocols: Vec<String>,
pub versions: Vec<ProtocolVersion>,
verifier: Arc<verify::ClientCertVerifier>,
}
impl ServerConfig {
pub fn new(client_cert_verifier: Arc<verify::ClientCertVerifier>) -> ServerConfig {
ServerConfig {
ciphersuites: ALL_CIPHERSUITES.to_vec(),
ignore_client_order: false,
mtu: None,
session_storage: Arc::new(handy::NoSessionStorage {}),
ticketer: Arc::new(handy::NeverProducesTickets {}),
alpn_protocols: Vec::new(),
cert_resolver: Arc::new(handy::FailResolveChain {}),
versions: vec![ ProtocolVersion::TLSv1_3, ProtocolVersion::TLSv1_2 ],
verifier: client_cert_verifier,
}
}
#[doc(hidden)]
pub fn get_verifier(&self) -> &verify::ClientCertVerifier {
self.verifier.as_ref()
}
pub fn set_persistence(&mut self, persist: Arc<StoresServerSessions + Send + Sync>) {
self.session_storage = persist;
}
pub fn set_single_cert(&mut self,
cert_chain: Vec<key::Certificate>,
key_der: key::PrivateKey) {
self.cert_resolver = Arc::new(handy::AlwaysResolvesChain::new_rsa(cert_chain, &key_der));
}
pub fn set_single_cert_with_ocsp_and_sct(&mut self,
cert_chain: Vec<key::Certificate>,
key_der: key::PrivateKey,
ocsp: Vec<u8>,
scts: Vec<u8>) {
let resolver = handy::AlwaysResolvesChain::new_rsa_with_extras(cert_chain,
&key_der,
ocsp,
scts);
self.cert_resolver = Arc::new(resolver);
}
pub fn set_protocols(&mut self, protocols: &[String]) {
self.alpn_protocols.clear();
self.alpn_protocols.extend_from_slice(protocols);
}
}
pub struct ServerSessionImpl {
pub config: Arc<ServerConfig>,
pub common: SessionCommon,
sni: Option<webpki::DNSName>,
pub alpn_protocol: Option<String>,
pub error: Option<TLSError>,
pub state: Option<Box<hs::State + Send + Sync>>,
pub client_cert_chain: Option<Vec<key::Certificate>>,
}
impl fmt::Debug for ServerSessionImpl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_struct("ServerSessionImpl").finish()
}
}
impl ServerSessionImpl {
pub fn new(server_config: &Arc<ServerConfig>) -> ServerSessionImpl {
let perhaps_client_auth = server_config.verifier.offer_client_auth();
ServerSessionImpl {
config: server_config.clone(),
common: SessionCommon::new(server_config.mtu, false),
sni: None,
alpn_protocol: None,
error: None,
state: Some(Box::new(hs::ExpectClientHello::new(perhaps_client_auth))),
client_cert_chain: None,
}
}
pub fn wants_read(&self) -> bool {
!self.common.has_readable_plaintext()
}
pub fn wants_write(&self) -> bool {
!self.common.sendable_tls.is_empty()
}
pub fn is_handshaking(&self) -> bool {
!self.common.traffic
}
pub fn set_buffer_limit(&mut self, len: usize) {
self.common.set_buffer_limit(len)
}
pub fn process_msg(&mut self, mut msg: Message) -> Result<(), TLSError> {
if self.common.is_tls13()
&& msg.is_content_type(ContentType::ChangeCipherSpec)
&& self.is_handshaking() {
trace!("Dropping CCS");
return Ok(());
}
if self.common.peer_encrypting {
let dm = self.common.decrypt_incoming(msg)?;
msg = dm;
}
if self.common.handshake_joiner.want_message(&msg) {
self.common.handshake_joiner.take_message(msg)
.ok_or_else(|| {
self.common.send_fatal_alert(AlertDescription::DecodeError);
TLSError::CorruptMessagePayload(ContentType::Handshake)
})?;
return self.process_new_handshake_messages();
}
msg.decode_payload();
if msg.is_content_type(ContentType::Alert) {
return self.common.process_alert(msg);
}
self.process_main_protocol(msg)
}
fn process_new_handshake_messages(&mut self) -> Result<(), TLSError> {
while let Some(msg) = self.common.handshake_joiner.frames.pop_front() {
self.process_main_protocol(msg)?;
}
Ok(())
}
fn queue_unexpected_alert(&mut self) {
self.common.send_fatal_alert(AlertDescription::UnexpectedMessage);
}
pub fn process_main_protocol(&mut self, msg: Message) -> Result<(), TLSError> {
if self.common.traffic && !self.common.is_tls13() &&
msg.is_handshake_type(HandshakeType::ClientHello) {
self.common.send_warning_alert(AlertDescription::NoRenegotiation);
return Ok(());
}
let st = self.state.take().unwrap();
st.check_message(&msg)
.map_err(|err| { self.queue_unexpected_alert(); err })?;
self.state = Some(st.handle(self, msg)?);
Ok(())
}
pub fn process_new_packets(&mut self) -> Result<(), TLSError> {
if let Some(ref err) = self.error {
return Err(err.clone());
}
if self.common.message_deframer.desynced {
return Err(TLSError::CorruptMessage);
}
while let Some(msg) = self.common.message_deframer.frames.pop_front() {
match self.process_msg(msg) {
Ok(_) => {}
Err(err) => {
self.error = Some(err.clone());
return Err(err);
}
}
}
Ok(())
}
pub fn get_peer_certificates(&self) -> Option<Vec<key::Certificate>> {
if self.client_cert_chain.is_none() {
return None;
}
let mut r = Vec::new();
for cert in self.client_cert_chain.as_ref().unwrap() {
r.push(cert.clone());
}
Some(r)
}
pub fn get_alpn_protocol(&self) -> Option<&str> {
self.alpn_protocol.as_ref().map(|s| s.as_ref())
}
pub fn get_protocol_version(&self) -> Option<ProtocolVersion> {
self.common.negotiated_version
}
pub fn get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite> {
self.common.get_suite()
}
pub fn get_sni(&self)-> Option<&webpki::DNSName> {
self.sni.as_ref()
}
pub fn set_sni(&mut self, value: webpki::DNSName) {
assert!(self.sni.is_none());
self.sni = Some(value)
}
}
#[derive(Debug)]
pub struct ServerSession {
imp: ServerSessionImpl,
}
impl ServerSession {
pub fn new(config: &Arc<ServerConfig>) -> ServerSession {
ServerSession { imp: ServerSessionImpl::new(config) }
}
pub fn get_sni_hostname(&self)-> Option<&str> {
self.imp.get_sni().map(|s| s.as_ref().into())
}
}
impl Session for ServerSession {
fn read_tls(&mut self, rd: &mut io::Read) -> io::Result<usize> {
self.imp.common.read_tls(rd)
}
fn write_tls(&mut self, wr: &mut io::Write) -> io::Result<usize> {
self.imp.common.write_tls(wr)
}
fn process_new_packets(&mut self) -> Result<(), TLSError> {
self.imp.process_new_packets()
}
fn wants_read(&self) -> bool {
self.imp.wants_read()
}
fn wants_write(&self) -> bool {
self.imp.wants_write()
}
fn is_handshaking(&self) -> bool {
self.imp.is_handshaking()
}
fn set_buffer_limit(&mut self, len: usize) {
self.imp.set_buffer_limit(len)
}
fn send_close_notify(&mut self) {
self.imp.common.send_close_notify()
}
fn get_peer_certificates(&self) -> Option<Vec<key::Certificate>> {
self.imp.get_peer_certificates()
}
fn get_alpn_protocol(&self) -> Option<&str> {
self.imp.get_alpn_protocol()
}
fn get_protocol_version(&self) -> Option<ProtocolVersion> {
self.imp.get_protocol_version()
}
fn export_keying_material(&self,
output: &mut [u8],
label: &[u8],
context: Option<&[u8]>) -> Result<(), TLSError> {
self.imp.common.export_keying_material(output, label, context)
}
fn get_negotiated_ciphersuite(&self) -> Option<&'static SupportedCipherSuite> {
self.imp.get_negotiated_ciphersuite()
}
}
impl io::Read for ServerSession {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.imp.common.read(buf)
}
}
impl io::Write for ServerSession {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.imp.common.send_some_plaintext(buf)
}
fn flush(&mut self) -> io::Result<()> {
self.imp.common.flush_plaintext();
Ok(())
}
}