use crate::cipher_suite::{CipherSuiteHash, CipherSuiteId};
use crypto::SecretVec;
use std::collections::{HashMap, VecDeque};
use std::fmt;
use std::sync::Mutex;
use std::time::{Duration, Instant};
pub const MAX_TICKET_LIFETIME: Duration = Duration::from_secs(604_800);
const MAX_SESSIONS_PER_NAME: usize = 8;
const MAX_NAMES: usize = 256;
#[derive(Clone)]
pub struct Tls13Session {
pub(crate) ticket: Vec<u8>,
pub(crate) secret: SecretVec,
pub(crate) suite: CipherSuiteId,
pub(crate) received: Instant,
pub(crate) lifetime: Duration,
pub(crate) age_add: u32,
pub(crate) max_early_data: u32,
pub(crate) peer_certificates: Vec<Vec<u8>>,
}
impl Tls13Session {
pub fn is_valid_at(&self, now: Instant) -> bool {
now.saturating_duration_since(self.received) < self.lifetime.min(MAX_TICKET_LIFETIME)
}
pub fn cipher_suite(&self) -> CipherSuiteId {
self.suite
}
pub fn max_early_data(&self) -> u32 {
self.max_early_data
}
pub fn peer_certificates(&self) -> &[Vec<u8>] {
&self.peer_certificates
}
pub fn limit_lifetime(&mut self, lifetime: Duration) {
self.lifetime = self.lifetime.min(lifetime);
}
pub(crate) fn obfuscated_age(&self, now: Instant) -> u32 {
let age = now.saturating_duration_since(self.received).as_millis() as u32;
age.wrapping_add(self.age_add)
}
}
impl fmt::Debug for Tls13Session {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Tls13Session")
.field("suite", &self.suite)
.field("lifetime", &self.lifetime)
.field("max_early_data", &self.max_early_data)
.field("ticket_len", &self.ticket.len())
.finish_non_exhaustive()
}
}
const DEFAULT_SESSION_CACHE_CAPACITY: usize = 1024;
#[derive(Clone)]
pub struct Dtls12Session {
pub(crate) session_id: Vec<u8>,
pub(crate) ticket: Option<Vec<u8>>,
pub(crate) master_secret: SecretVec,
pub(crate) cipher_suite: CipherSuiteId,
pub(crate) extended_master_secret: bool,
pub(crate) peer_certificates: Vec<Vec<u8>>,
pub(crate) peer_certificates_verified: bool,
pub(crate) server_name: String,
pub(crate) created: Instant,
pub(crate) lifetime: Duration,
}
impl Dtls12Session {
pub fn is_valid_at(&self, now: Instant) -> bool {
now.saturating_duration_since(self.created) < self.lifetime
}
pub fn cipher_suite(&self) -> CipherSuiteId {
self.cipher_suite
}
pub fn session_id(&self) -> &[u8] {
&self.session_id
}
pub fn has_ticket(&self) -> bool {
self.ticket.is_some()
}
pub fn peer_certificates(&self) -> &[Vec<u8>] {
&self.peer_certificates
}
}
impl fmt::Debug for Dtls12Session {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Dtls12Session")
.field("session_id", &self.session_id)
.field("cipher_suite", &self.cipher_suite)
.field("extended_master_secret", &self.extended_master_secret)
.field("has_ticket", &self.ticket.is_some())
.field("lifetime", &self.lifetime)
.finish_non_exhaustive()
}
}
pub trait SessionStore: Send + Sync {
fn put(&self, server_name: &str, session: Tls13Session);
fn take(&self, server_name: &str) -> Option<Tls13Session>;
fn put_dtls12(&self, _server_name: &str, _session: Dtls12Session) {}
fn take_dtls12(&self, _server_name: &str) -> Option<Dtls12Session> {
None
}
fn forget_dtls12(&self, _server_name: &str, _session_id: &[u8]) {}
}
#[derive(Default)]
pub struct MemorySessionStore {
sessions: Mutex<HashMap<String, VecDeque<Tls13Session>>>,
dtls12: Mutex<HashMap<String, VecDeque<Dtls12Session>>>,
}
impl MemorySessionStore {
pub fn new() -> Self {
Self::default()
}
pub fn len(&self, server_name: &str) -> usize {
self.sessions
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(server_name)
.map_or(0, VecDeque::len)
}
pub fn len_dtls12(&self, server_name: &str) -> usize {
self.dtls12
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.get(server_name)
.map_or(0, VecDeque::len)
}
}
impl fmt::Debug for MemorySessionStore {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MemorySessionStore").finish_non_exhaustive()
}
}
impl SessionStore for MemorySessionStore {
fn put(&self, server_name: &str, session: Tls13Session) {
let mut sessions = self
.sessions
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !sessions.contains_key(server_name) && sessions.len() >= MAX_NAMES {
return;
}
let list = sessions.entry(server_name.to_owned()).or_default();
list.push_front(session);
list.truncate(MAX_SESSIONS_PER_NAME);
}
fn take(&self, server_name: &str) -> Option<Tls13Session> {
let mut sessions = self
.sessions
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let list = sessions.get_mut(server_name)?;
let session = list.pop_front();
if list.is_empty() {
sessions.remove(server_name);
}
session
}
fn put_dtls12(&self, server_name: &str, session: Dtls12Session) {
let mut sessions = self
.dtls12
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if !sessions.contains_key(server_name) && sessions.len() >= MAX_NAMES {
return;
}
let list = sessions.entry(server_name.to_owned()).or_default();
list.push_front(session);
list.truncate(MAX_SESSIONS_PER_NAME);
}
fn take_dtls12(&self, server_name: &str) -> Option<Dtls12Session> {
let mut sessions = self
.dtls12
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let list = sessions.get_mut(server_name)?;
let session = list.pop_front();
if list.is_empty() {
sessions.remove(server_name);
}
session
}
fn forget_dtls12(&self, server_name: &str, session_id: &[u8]) {
let mut sessions = self
.dtls12
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
if let Some(list) = sessions.get_mut(server_name) {
list.retain(|session| session.session_id != session_id);
if list.is_empty() {
sessions.remove(server_name);
}
}
}
}
pub trait SessionCache: Send + Sync {
fn put(&self, session: Dtls12Session);
fn get(&self, session_id: &[u8]) -> Option<Dtls12Session>;
fn remove(&self, session_id: &[u8]);
}
#[derive(Default)]
struct CachedSessions {
by_id: HashMap<Vec<u8>, Dtls12Session>,
order: VecDeque<Vec<u8>>,
}
pub struct MemorySessionCache {
capacity: usize,
sessions: Mutex<CachedSessions>,
}
impl MemorySessionCache {
pub fn new(capacity: usize) -> Self {
Self {
capacity: capacity.max(1),
sessions: Mutex::new(CachedSessions::default()),
}
}
pub fn len(&self) -> usize {
self.sessions
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.by_id
.len()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Default for MemorySessionCache {
fn default() -> Self {
Self::new(DEFAULT_SESSION_CACHE_CAPACITY)
}
}
impl fmt::Debug for MemorySessionCache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("MemorySessionCache")
.field("capacity", &self.capacity)
.finish_non_exhaustive()
}
}
impl SessionCache for MemorySessionCache {
fn put(&self, session: Dtls12Session) {
let mut guard = self
.sessions
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let CachedSessions { by_id, order } = &mut *guard;
let id = session.session_id.clone();
if by_id.insert(id.clone(), session).is_none() {
order.push_back(id);
}
while by_id.len() > self.capacity {
let Some(oldest) = order.pop_front() else {
break;
};
by_id.remove(&oldest);
}
}
fn get(&self, session_id: &[u8]) -> Option<Dtls12Session> {
self.sessions
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.by_id
.get(session_id)
.cloned()
}
fn remove(&self, session_id: &[u8]) {
let mut guard = self
.sessions
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner());
let CachedSessions { by_id, order } = &mut *guard;
if by_id.remove(session_id).is_some() {
order.retain(|id| id.as_slice() != session_id);
}
}
}
#[derive(Clone)]
pub struct ExternalPsk {
pub(crate) identity: Vec<u8>,
pub(crate) secret: SecretVec,
pub(crate) hash: CipherSuiteHash,
}
impl ExternalPsk {
pub fn new(identity: Vec<u8>, secret: Vec<u8>) -> Self {
Self {
identity,
secret: SecretVec::new(secret),
hash: CipherSuiteHash::Sha256,
}
}
pub fn with_hash(mut self, hash: CipherSuiteHash) -> Self {
self.hash = hash;
self
}
pub fn identity(&self) -> &[u8] {
&self.identity
}
}
impl fmt::Debug for ExternalPsk {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExternalPsk")
.field("identity", &self.identity)
.field("hash", &self.hash)
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct SessionTicketIssuer(pub(crate) std::sync::Arc<crate::dtls13::psk::TicketIssuer>);
impl SessionTicketIssuer {
pub fn new(
provider: &dyn crypto::RTCCryptoProvider,
count: u8,
lifetime: std::time::Duration,
) -> shared::error::Result<Self> {
Ok(Self(std::sync::Arc::new(
crate::dtls13::psk::TicketIssuer::new(provider, count, lifetime)?,
)))
}
pub fn retire(&self) {
self.0.retire();
}
pub fn is_retired(&self) -> bool {
self.0.is_retired()
}
}
impl fmt::Debug for SessionTicketIssuer {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SessionTicketIssuer")
.field("count", &self.0.count)
.field("lifetime", &self.0.lifetime)
.finish_non_exhaustive()
}
}