Skip to main content

rtci_dtls/
session.rs

1//! Pre-shared keys for DTLS 1.3 (RFC 8446 sections 2.2, 4.2.9 to 4.2.11 and 4.6.1, as RFC
2//! 9147 carries them): session resumption with tickets, and external PSKs.
3//!
4//! A server that is configured to
5//! ([`ConfigBuilder::with_session_tickets`](crate::config::ConfigBuilder::with_session_tickets))
6//! sends NewSessionTicket messages after a handshake. Each ticket is the server's own,
7//! encrypted under a key only the server holds, and carries the resumption secret, so the
8//! server keeps no state per ticket beyond the record that a ticket has been used: a ticket is
9//! accepted once (RFC 8446 section 8.1, appendix C.4). A client that is given a
10//! [`SessionStore`] ([`ConfigBuilder::with_session_store`](crate::config::ConfigBuilder::with_session_store))
11//! keeps the tickets it receives, keyed by its configured server name, and offers one (once) in
12//! its next ClientHello to that name.
13//!
14//! A resumed handshake has no Certificate or CertificateVerify: the peer is the one that held
15//! the ticket's secret, which was made in a handshake that authenticated it. The certificates
16//! of that handshake are carried with the ticket and are what the association reports, and the
17//! configured
18//! [`ConfigBuilder::with_verify_peer_certificate`](crate::config::ConfigBuilder::with_verify_peer_certificate)
19//! check runs on them again. With a check configured, a ticket that carries no certificate
20//! where one should be is not resumed as if it had passed: a client fails the handshake
21//! (`bad_certificate`), and a server that asks its clients for a certificate runs a full
22//! handshake instead. A server that asks for none
23//! ([`ClientAuthType::NoClientCert`](crate::config::ClientAuthType::NoClientCert)) resumes
24//! such a ticket: the first handshake had no client certificate to check either.
25//!
26//! An external PSK ([`ExternalPsk`], RFC 8446 sections 2.2 and 4.2.11) is not a resumption:
27//! it was never made by a certificate handshake, carries no certificate, and authenticates
28//! both sides by possession of the key. The peer-certificate check is not called for it.
29//!
30//! Only the `psk_dhe_ke` mode is offered and accepted by default: the PSK is combined with a
31//! fresh (EC)DHE exchange, which keeps forward secrecy. `psk_ke` (the PSK alone) is an explicit
32//! option ([`ConfigBuilder::with_psk_without_key_exchange`](crate::config::ConfigBuilder::with_psk_without_key_exchange)).
33//!
34//! DTLS 1.2 resumes sessions too (RFC 5246 section 7.3, the abbreviated handshake): by session
35//! id, from a [`SessionCache`] the server keeps
36//! ([`ConfigBuilder::with_session_cache`](crate::config::ConfigBuilder::with_session_cache)),
37//! or by a ticket the server seals for the client (RFC 5077, with
38//! [`ConfigBuilder::with_session_tickets`](crate::config::ConfigBuilder::with_session_tickets)).
39//! A client keeps its [`Dtls12Session`]s in the same [`SessionStore`]. Only sessions made with
40//! the extended master secret are resumed (RFC 7627 section 5.3), with the master secret of
41//! the session and fresh randoms: no key exchange, no Certificate, no CertificateVerify. The
42//! certificates of the full handshake are what the association reports, and the configured
43//! peer-certificate checks run on them again, with the same rule for a session that carries
44//! no certificate as for a DTLS 1.3 ticket. A session is forgotten when an association that
45//! used it fails (RFC 5246 sections 7.2 and 7.2.2).
46//!
47//! **DTLS 1.2 resumption has no forward secrecy against what holds the session.** A resumed
48//! DTLS 1.2 association runs no key exchange: its keys are the session's master secret and
49//! two public randoms. The server's [`SessionCache`], the client's [`SessionStore`] and,
50//! for RFC 5077 tickets, the server's ticket key (the ticket is the master secret sealed
51//! under it, sent in the clear part of the handshake) each open, if obtained later, the
52//! recorded traffic of the association the session came from and of every one resumed from
53//! it. DTLS 1.3 resumption does not have this cost (`psk_dhe_ke`: a new (EC)DHE exchange
54//! every time). Both versions resume by default once tickets, a cache or a store are
55//! configured;
56//! [`ConfigBuilder::with_dtls12_resumption`](crate::config::ConfigBuilder::with_dtls12_resumption)`(false)`
57//! takes DTLS 1.2 out of resumption and leaves DTLS 1.3's, and is what an application that
58//! does not need DTLS 1.2 resumption should set.
59//!
60//! WebRTC authenticates every DTLS association by the certificate fingerprints its SDP carries.
61//! The peer connection of the `rtci` crate resumes only within one connection, when the
62//! application turns it on (RFC 5764 section 3: the transports of unbundled sections share
63//! the session of the first), and in DTLS 1.3 only (`psk_dhe_ke`): it gives the first
64//! association of each such transport the connection's own store or ticket keys
65//! ([`SessionTicketIssuer`]) with DTLS 1.2 resumption off, and every other association none,
66//! so that it neither offers nor accepts a resumption.
67
68use crate::cipher_suite::{CipherSuiteHash, CipherSuiteId};
69use crypto::SecretVec;
70use std::collections::{HashMap, VecDeque};
71use std::fmt;
72use std::sync::Mutex;
73use std::time::{Duration, Instant};
74
75/// The longest a ticket may be used for (RFC 8446 section 4.6.1: seven days).
76pub const MAX_TICKET_LIFETIME: Duration = Duration::from_secs(604_800);
77
78/// How many tickets [`MemorySessionStore`] keeps for one server name.
79const MAX_SESSIONS_PER_NAME: usize = 8;
80/// How many server names [`MemorySessionStore`] keeps tickets for.
81const MAX_NAMES: usize = 256;
82
83/// A ticket a client received in a NewSessionTicket, with what it needs to resume: the
84/// resumption PSK derived for it, the suite it belongs to, and the certificates of the
85/// handshake it came from. Opaque to applications; a [`SessionStore`] keeps it.
86#[derive(Clone)]
87pub struct Tls13Session {
88    pub(crate) ticket: Vec<u8>,
89    pub(crate) secret: SecretVec,
90    pub(crate) suite: CipherSuiteId,
91    pub(crate) received: Instant,
92    pub(crate) lifetime: Duration,
93    pub(crate) age_add: u32,
94    pub(crate) max_early_data: u32,
95    pub(crate) peer_certificates: Vec<Vec<u8>>,
96}
97
98impl Tls13Session {
99    /// Whether the ticket may still be offered at `now` (RFC 8446 section 4.6.1: not after
100    /// its lifetime, and never after seven days).
101    pub fn is_valid_at(&self, now: Instant) -> bool {
102        now.saturating_duration_since(self.received) < self.lifetime.min(MAX_TICKET_LIFETIME)
103    }
104
105    /// The cipher suite of the handshake that issued the ticket. It may be resumed only with
106    /// a suite of the same hash (RFC 8446 section 4.6.1).
107    pub fn cipher_suite(&self) -> CipherSuiteId {
108        self.suite
109    }
110
111    /// The most early data the server said it would take with this ticket, 0 for none.
112    pub fn max_early_data(&self) -> u32 {
113        self.max_early_data
114    }
115
116    /// The server's certificate chain in the handshake the ticket came from: what a resumption
117    /// with it reports, and what the configured peer-certificate check runs on again.
118    pub fn peer_certificates(&self) -> &[Vec<u8>] {
119        &self.peer_certificates
120    }
121
122    /// Shortens the time the ticket may be offered for to at most `lifetime` from its
123    /// arrival (a client may keep a ticket for less than the server allows, RFC 8446
124    /// section 4.6.1: "Clients MUST NOT cache tickets for longer than 7 days").
125    pub fn limit_lifetime(&mut self, lifetime: Duration) {
126        self.lifetime = self.lifetime.min(lifetime);
127    }
128
129    /// The `obfuscated_ticket_age` of an offer made at `now` (RFC 8446 section 4.2.11.1): the
130    /// milliseconds since the ticket arrived, plus `ticket_age_add`, modulo 2^32.
131    pub(crate) fn obfuscated_age(&self, now: Instant) -> u32 {
132        let age = now.saturating_duration_since(self.received).as_millis() as u32;
133        age.wrapping_add(self.age_add)
134    }
135}
136
137impl fmt::Debug for Tls13Session {
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        f.debug_struct("Tls13Session")
140            .field("suite", &self.suite)
141            .field("lifetime", &self.lifetime)
142            .field("max_early_data", &self.max_early_data)
143            .field("ticket_len", &self.ticket.len())
144            .finish_non_exhaustive()
145    }
146}
147
148/// How many sessions [`MemorySessionCache`] keeps by default.
149const DEFAULT_SESSION_CACHE_CAPACITY: usize = 1024;
150
151/// A DTLS 1.2 session (RFC 5246 section 7.3) that a handshake may resume: what the full
152/// handshake that made it agreed on. A server keeps it in its [`SessionCache`] under its
153/// session id, or seals it into a ticket (RFC 5077); a client keeps it in its
154/// [`SessionStore`], with the ticket if the server gave one. Opaque to applications.
155#[derive(Clone)]
156pub struct Dtls12Session {
157    /// The session id of the ServerHello that established or last resumed it (empty when the
158    /// server gave a ticket and no id).
159    pub(crate) session_id: Vec<u8>,
160    /// Client: the ticket (RFC 5077) to present, if the server gave one.
161    pub(crate) ticket: Option<Vec<u8>>,
162    pub(crate) master_secret: SecretVec,
163    pub(crate) cipher_suite: CipherSuiteId,
164    /// Made with the extended master secret (RFC 7627). A session made without it is never
165    /// resumed by this crate (section 5.3); the flag is kept so that the rules can be applied
166    /// to one from elsewhere.
167    pub(crate) extended_master_secret: bool,
168    /// The peer's certificate chain in the full handshake.
169    pub(crate) peer_certificates: Vec<Vec<u8>>,
170    /// Server: the client's chain was verified (client authentication).
171    pub(crate) peer_certificates_verified: bool,
172    /// The server name of the full handshake (RFC 6066 section 3: a server does not resume a
173    /// session for another name).
174    pub(crate) server_name: String,
175    pub(crate) created: Instant,
176    pub(crate) lifetime: Duration,
177}
178
179impl Dtls12Session {
180    /// Whether the session may still be resumed at `now`: not after its lifetime (RFC 5246
181    /// appendix F.1.4 suggests no more than 24 hours).
182    pub fn is_valid_at(&self, now: Instant) -> bool {
183        now.saturating_duration_since(self.created) < self.lifetime
184    }
185
186    /// The cipher suite of the session: a resumption uses the same (RFC 5246 7.4.1.3).
187    pub fn cipher_suite(&self) -> CipherSuiteId {
188        self.cipher_suite
189    }
190
191    /// The session id, empty for a session known by its ticket only.
192    pub fn session_id(&self) -> &[u8] {
193        &self.session_id
194    }
195
196    /// Whether the client holds a ticket (RFC 5077) for the session.
197    pub fn has_ticket(&self) -> bool {
198        self.ticket.is_some()
199    }
200
201    /// The peer's certificate chain in the full handshake: what a resumption of the session
202    /// reports, and what the configured peer-certificate check runs on again.
203    pub fn peer_certificates(&self) -> &[Vec<u8>] {
204        &self.peer_certificates
205    }
206}
207
208impl fmt::Debug for Dtls12Session {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        f.debug_struct("Dtls12Session")
211            .field("session_id", &self.session_id)
212            .field("cipher_suite", &self.cipher_suite)
213            .field("extended_master_secret", &self.extended_master_secret)
214            .field("has_ticket", &self.ticket.is_some())
215            .field("lifetime", &self.lifetime)
216            .finish_non_exhaustive()
217    }
218}
219
220/// Where a client keeps the tickets servers give it, keyed by server name.
221///
222/// [`take`](SessionStore::take) removes what it returns: a ticket is offered once (RFC 8446
223/// appendix C.4), so that two handshakes cannot be linked by it.
224///
225/// The DTLS 1.2 methods have defaults that keep nothing, so a store written for DTLS 1.3 only
226/// resumes no DTLS 1.2 session. A store that keeps DTLS 1.2 sessions must implement
227/// [`forget_dtls12`](SessionStore::forget_dtls12): RFC 5246 section 7.2.2 forbids resuming
228/// a session whose connection ended with a fatal alert.
229pub trait SessionStore: Send + Sync {
230    /// Keeps `session`, received from the server configured as `server_name`.
231    fn put(&self, server_name: &str, session: Tls13Session);
232    /// Takes the most recent session for `server_name`, if there is one.
233    fn take(&self, server_name: &str) -> Option<Tls13Session>;
234
235    /// Keeps a DTLS 1.2 session made with the server configured as `server_name`.
236    fn put_dtls12(&self, _server_name: &str, _session: Dtls12Session) {}
237    /// Takes the most recent DTLS 1.2 session for `server_name`. A session id session that
238    /// is resumed is put back; a ticket is offered once.
239    fn take_dtls12(&self, _server_name: &str) -> Option<Dtls12Session> {
240        None
241    }
242    /// Forgets the DTLS 1.2 session `session_id` of `server_name`: its connection failed.
243    fn forget_dtls12(&self, _server_name: &str, _session_id: &[u8]) {}
244}
245
246/// A [`SessionStore`] in memory: a few tickets per server name, most recent first.
247#[derive(Default)]
248pub struct MemorySessionStore {
249    sessions: Mutex<HashMap<String, VecDeque<Tls13Session>>>,
250    dtls12: Mutex<HashMap<String, VecDeque<Dtls12Session>>>,
251}
252
253impl MemorySessionStore {
254    /// An empty store.
255    pub fn new() -> Self {
256        Self::default()
257    }
258
259    /// How many tickets the store holds for `server_name`.
260    pub fn len(&self, server_name: &str) -> usize {
261        self.sessions
262            .lock()
263            .unwrap_or_else(|poisoned| poisoned.into_inner())
264            .get(server_name)
265            .map_or(0, VecDeque::len)
266    }
267
268    /// How many DTLS 1.2 sessions the store holds for `server_name`.
269    pub fn len_dtls12(&self, server_name: &str) -> usize {
270        self.dtls12
271            .lock()
272            .unwrap_or_else(|poisoned| poisoned.into_inner())
273            .get(server_name)
274            .map_or(0, VecDeque::len)
275    }
276}
277
278impl fmt::Debug for MemorySessionStore {
279    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
280        f.debug_struct("MemorySessionStore").finish_non_exhaustive()
281    }
282}
283
284impl SessionStore for MemorySessionStore {
285    fn put(&self, server_name: &str, session: Tls13Session) {
286        let mut sessions = self
287            .sessions
288            .lock()
289            .unwrap_or_else(|poisoned| poisoned.into_inner());
290        if !sessions.contains_key(server_name) && sessions.len() >= MAX_NAMES {
291            return;
292        }
293        let list = sessions.entry(server_name.to_owned()).or_default();
294        list.push_front(session);
295        list.truncate(MAX_SESSIONS_PER_NAME);
296    }
297
298    fn take(&self, server_name: &str) -> Option<Tls13Session> {
299        let mut sessions = self
300            .sessions
301            .lock()
302            .unwrap_or_else(|poisoned| poisoned.into_inner());
303        let list = sessions.get_mut(server_name)?;
304        let session = list.pop_front();
305        if list.is_empty() {
306            sessions.remove(server_name);
307        }
308        session
309    }
310
311    fn put_dtls12(&self, server_name: &str, session: Dtls12Session) {
312        let mut sessions = self
313            .dtls12
314            .lock()
315            .unwrap_or_else(|poisoned| poisoned.into_inner());
316        if !sessions.contains_key(server_name) && sessions.len() >= MAX_NAMES {
317            return;
318        }
319        let list = sessions.entry(server_name.to_owned()).or_default();
320        list.push_front(session);
321        list.truncate(MAX_SESSIONS_PER_NAME);
322    }
323
324    fn take_dtls12(&self, server_name: &str) -> Option<Dtls12Session> {
325        let mut sessions = self
326            .dtls12
327            .lock()
328            .unwrap_or_else(|poisoned| poisoned.into_inner());
329        let list = sessions.get_mut(server_name)?;
330        let session = list.pop_front();
331        if list.is_empty() {
332            sessions.remove(server_name);
333        }
334        session
335    }
336
337    fn forget_dtls12(&self, server_name: &str, session_id: &[u8]) {
338        let mut sessions = self
339            .dtls12
340            .lock()
341            .unwrap_or_else(|poisoned| poisoned.into_inner());
342        if let Some(list) = sessions.get_mut(server_name) {
343            list.retain(|session| session.session_id != session_id);
344            if list.is_empty() {
345                sessions.remove(server_name);
346            }
347        }
348    }
349}
350
351/// Where a DTLS 1.2 server keeps the sessions it may resume by session id (RFC 5246 sections
352/// 7.3, 7.4.1.3). A server without one gives no session id and resumes by ticket only, if
353/// it issues tickets.
354pub trait SessionCache: Send + Sync {
355    /// Keeps `session` under its session id.
356    fn put(&self, session: Dtls12Session);
357    /// The session `session_id`, if it is kept.
358    fn get(&self, session_id: &[u8]) -> Option<Dtls12Session>;
359    /// Forgets the session `session_id` (RFC 5246 7.2: its connection failed).
360    fn remove(&self, session_id: &[u8]);
361}
362
363/// The sessions of a [`MemorySessionCache`], by id, and their ids oldest first.
364#[derive(Default)]
365struct CachedSessions {
366    by_id: HashMap<Vec<u8>, Dtls12Session>,
367    order: VecDeque<Vec<u8>>,
368}
369
370/// A [`SessionCache`] in memory, of a bounded size: the oldest session goes first.
371pub struct MemorySessionCache {
372    capacity: usize,
373    sessions: Mutex<CachedSessions>,
374}
375
376impl MemorySessionCache {
377    /// A cache of at most `capacity` sessions.
378    pub fn new(capacity: usize) -> Self {
379        Self {
380            capacity: capacity.max(1),
381            sessions: Mutex::new(CachedSessions::default()),
382        }
383    }
384
385    /// How many sessions the cache holds.
386    pub fn len(&self) -> usize {
387        self.sessions
388            .lock()
389            .unwrap_or_else(|poisoned| poisoned.into_inner())
390            .by_id
391            .len()
392    }
393
394    /// Whether the cache holds no session.
395    pub fn is_empty(&self) -> bool {
396        self.len() == 0
397    }
398}
399
400impl Default for MemorySessionCache {
401    fn default() -> Self {
402        Self::new(DEFAULT_SESSION_CACHE_CAPACITY)
403    }
404}
405
406impl fmt::Debug for MemorySessionCache {
407    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
408        f.debug_struct("MemorySessionCache")
409            .field("capacity", &self.capacity)
410            .finish_non_exhaustive()
411    }
412}
413
414impl SessionCache for MemorySessionCache {
415    fn put(&self, session: Dtls12Session) {
416        let mut guard = self
417            .sessions
418            .lock()
419            .unwrap_or_else(|poisoned| poisoned.into_inner());
420        let CachedSessions { by_id, order } = &mut *guard;
421        let id = session.session_id.clone();
422        if by_id.insert(id.clone(), session).is_none() {
423            order.push_back(id);
424        }
425        while by_id.len() > self.capacity {
426            let Some(oldest) = order.pop_front() else {
427                break;
428            };
429            by_id.remove(&oldest);
430        }
431    }
432
433    fn get(&self, session_id: &[u8]) -> Option<Dtls12Session> {
434        self.sessions
435            .lock()
436            .unwrap_or_else(|poisoned| poisoned.into_inner())
437            .by_id
438            .get(session_id)
439            .cloned()
440    }
441
442    fn remove(&self, session_id: &[u8]) {
443        let mut guard = self
444            .sessions
445            .lock()
446            .unwrap_or_else(|poisoned| poisoned.into_inner());
447        let CachedSessions { by_id, order } = &mut *guard;
448        if by_id.remove(session_id).is_some() {
449            order.retain(|id| id.as_slice() != session_id);
450        }
451    }
452}
453
454/// An external pre-shared key for DTLS 1.3 (RFC 8446 section 2.2): an identity both sides
455/// know and a secret both hold, provisioned out of band. A client offers each it is configured
456/// with; a server accepts the one whose identity it has, in place of certificates.
457///
458/// The secret should have at least 128 bits of entropy (RFC 9257 section 4): a low-entropy
459/// key, such as a password, can be found by anyone who sees one handshake.
460#[derive(Clone)]
461pub struct ExternalPsk {
462    pub(crate) identity: Vec<u8>,
463    pub(crate) secret: SecretVec,
464    pub(crate) hash: CipherSuiteHash,
465}
466
467impl ExternalPsk {
468    /// A PSK for the SHA-256 suites.
469    pub fn new(identity: Vec<u8>, secret: Vec<u8>) -> Self {
470        Self {
471            identity,
472            secret: SecretVec::new(secret),
473            hash: CipherSuiteHash::Sha256,
474        }
475    }
476
477    /// The same PSK for the SHA-384 suite (`TLS_AES_256_GCM_SHA384`) instead: a PSK is bound
478    /// to one hash (RFC 8446 section 4.2.11).
479    pub fn with_hash(mut self, hash: CipherSuiteHash) -> Self {
480        self.hash = hash;
481        self
482    }
483
484    /// The identity.
485    pub fn identity(&self) -> &[u8] {
486        &self.identity
487    }
488}
489
490impl fmt::Debug for ExternalPsk {
491    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
492        f.debug_struct("ExternalPsk")
493            .field("identity", &self.identity)
494            .field("hash", &self.hash)
495            .finish_non_exhaustive()
496    }
497}
498
499/// The keys a DTLS server seals its session tickets under (DTLS 1.3 tickets, RFC 8446 section
500/// 4.6.1, and DTLS 1.2 tickets, RFC 5077), with the record of the tickets already accepted,
501/// for several configurations to share
502/// ([`ConfigBuilder::with_session_ticket_issuer`](crate::config::ConfigBuilder::with_session_ticket_issuer)):
503/// a ticket one of them issued is accepted, once, by any of them. A configuration given none
504/// makes keys of its own when it is built ([`ConfigBuilder::with_session_tickets`](crate::config::ConfigBuilder::with_session_tickets)),
505/// which no other configuration can open. Clones share the same keys.
506/// [`Self::retire`] wipes them before the last holder is dropped.
507#[derive(Clone)]
508pub struct SessionTicketIssuer(pub(crate) std::sync::Arc<crate::dtls13::psk::TicketIssuer>);
509
510impl SessionTicketIssuer {
511    /// New random keys, from `provider`'s random source: `count` DTLS 1.3 tickets after each
512    /// handshake (any count above 0 also issues DTLS 1.2 tickets, one per handshake to a client
513    /// that asks for one), each valid for `lifetime` (at most seven days).
514    pub fn new(
515        provider: &dyn crypto::RTCCryptoProvider,
516        count: u8,
517        lifetime: std::time::Duration,
518    ) -> shared::error::Result<Self> {
519        Ok(Self(std::sync::Arc::new(
520            crate::dtls13::psk::TicketIssuer::new(provider, count, lifetime)?,
521        )))
522    }
523
524    /// Wipes the keys for good, in every clone and every configuration that shares them: the
525    /// key bytes are zeroized, no ticket is issued from now on, and none of the tickets
526    /// issued so far is accepted (a client that offers one gets a full handshake). For an
527    /// application that is done with the sessions these keys protect before the last
528    /// configuration holding them is dropped (the keys are also zeroized on drop).
529    /// Associations already established are not affected.
530    pub fn retire(&self) {
531        self.0.retire();
532    }
533
534    /// Whether the keys were wiped ([`Self::retire`]).
535    pub fn is_retired(&self) -> bool {
536        self.0.is_retired()
537    }
538}
539
540impl fmt::Debug for SessionTicketIssuer {
541    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
542        f.debug_struct("SessionTicketIssuer")
543            .field("count", &self.0.count)
544            .field("lifetime", &self.0.lifetime)
545            .finish_non_exhaustive()
546    }
547}