simoom-tls 0.1.0

Sans-io TLS 1.3 server and client for simoom, with QUIC support (RFC 9001).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Server and client configuration: certificates and SNI, client authentication, ALPN, session
//! tickets with rotating keys, and the time source.

use super::{CipherSuite, Error, NamedGroup, Result};
use crate::crypto::gcm::AesGcm;
use crate::crypto::rng;
use crate::keys::PrivateKey;
use crate::x509::{Certificate, RootStore};
#[cfg(feature = "client")]
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Mutex};

/// Wall-clock time in Unix milliseconds. The protocol code never reads a clock itself: ticket
/// ages and certificate validity use this. Tests inject fixed times.
pub trait TimeSource: Send + Sync {
    fn unix_millis(&self) -> u64;
}

/// The operating system clock.
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemClock;

impl TimeSource for SystemClock {
    fn unix_millis(&self) -> u64 {
        std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as u64).unwrap_or(0)
    }
}

/// A certificate chain (leaf first, DER) with its private key.
#[derive(Clone, Debug)]
pub struct CertifiedKey {
    pub chain: Vec<Vec<u8>>,
    pub key: PrivateKey,
    /// The leaf's DNS names for SNI (its SAN entries, or else its common name), taken from
    /// the one parse in [`CertifiedKey::new`].
    names: Vec<String>,
}

impl CertifiedKey {
    /// Checks that the key matches the leaf certificate.
    pub fn new(chain: Vec<Vec<u8>>, key: PrivateKey) -> Result<CertifiedKey> {
        let leaf = chain.first().ok_or_else(|| Error::Config("empty certificate chain".into()))?;
        let cert = Certificate::from_der(leaf).map_err(|e| Error::Config(format!("bad certificate: {e}")))?;
        match &cert.public_key {
            Some(pk) if pk.same_as(&key.public_key()) => {
                let names = if cert.has_san { cert.dns_names } else { cert.subject.common_name().map(|s| vec![s.to_ascii_lowercase()]).unwrap_or_default() };
                Ok(CertifiedKey { chain, key, names })
            }
            Some(_) => Err(Error::Config("the private key does not match the certificate".into())),
            None => Err(Error::Config("unsupported certificate key type".into())),
        }
    }

    /// From PEM text: every CERTIFICATE block (leaf first) and the first private key.
    pub fn from_pem(cert_pem: &[u8], key_pem: &[u8]) -> Result<CertifiedKey> {
        let chain: Vec<Vec<u8>> = crate::pem::parse_pem(cert_pem)
            .map_err(Error::Config)?
            .into_iter()
            .filter(|b| b.label == "CERTIFICATE")
            .map(|b| b.der)
            .collect();
        let key = PrivateKey::from_pem(key_pem).map_err(Error::Config)?;
        CertifiedKey::new(chain, key)
    }

    /// From DER: the chain and a key in PKCS#8, SEC1 or PKCS#1.
    pub fn from_der(chain: Vec<Vec<u8>>, key_der: &[u8]) -> Result<CertifiedKey> {
        let key = PrivateKey::from_der(key_der).map_err(Error::Config)?;
        CertifiedKey::new(chain, key)
    }

    /// The leaf's DNS names used for SNI selection (SAN entries, or else the common name).
    pub fn names(&self) -> &[String] {
        &self.names
    }
}

/// Client certificate authentication on a server.
#[derive(Clone, Debug, Default)]
pub enum ClientAuth {
    /// No CertificateRequest.
    #[default]
    None,
    /// Request a certificate; accept clients without one, validate the ones that send one.
    Optional(RootStore),
    /// Require a valid client certificate.
    Required(RootStore),
}

/// Encrypts and decrypts session tickets with AES-256-GCM under keys that rotate every
/// `rotate_secs`; the previous key stays valid for one more period.
pub struct Ticketer {
    keys: Mutex<TicketKeys>,
    rotate_ms: u64,
}

struct TicketKey {
    id: [u8; 8],
    aead: AesGcm,
    created_ms: u64,
}

struct TicketKeys {
    current: Option<TicketKey>,
    previous: Option<TicketKey>,
}

impl std::fmt::Debug for Ticketer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Ticketer(rotate every {} s)", self.rotate_ms / 1000)
    }
}

impl Ticketer {
    pub fn new(rotate_secs: u32) -> Ticketer {
        Ticketer { keys: Mutex::new(TicketKeys { current: None, previous: None }), rotate_ms: rotate_secs.max(1) as u64 * 1000 }
    }

    fn fresh(now: u64) -> TicketKey {
        let mut k = rng::array::<32>();
        let key = TicketKey { id: rng::array(), aead: AesGcm::new(&k), created_ms: now };
        crate::util::zeroize(&mut k);
        key
    }

    fn rotate(&self, keys: &mut TicketKeys, now: u64) {
        let stale = match &keys.current {
            None => true,
            Some(k) => now.saturating_sub(k.created_ms) >= self.rotate_ms,
        };
        if stale {
            keys.previous = keys.current.take();
            keys.current = Some(Self::fresh(now));
            if let Some(p) = &keys.previous {
                if now.saturating_sub(p.created_ms) >= 2 * self.rotate_ms {
                    keys.previous = None;
                }
            }
        }
    }

    /// key id (8) || nonce (12) || ciphertext || tag (16).
    pub(crate) fn seal(&self, now: u64, plain: &[u8]) -> Vec<u8> {
        let mut keys = self.keys.lock().unwrap_or_else(|e| e.into_inner());
        self.rotate(&mut keys, now);
        let k = keys.current.as_ref().expect("current key");
        let nonce = rng::array::<12>();
        let mut out = Vec::with_capacity(36 + plain.len());
        out.extend_from_slice(&k.id);
        out.extend_from_slice(&nonce);
        let start = out.len();
        out.extend_from_slice(plain);
        let tag = k.aead.seal(&nonce, &k.id, &mut out[start..]);
        out.extend_from_slice(&tag);
        out
    }

    pub(crate) fn open(&self, now: u64, ticket: &[u8]) -> Option<Vec<u8>> {
        if ticket.len() < 36 {
            return None;
        }
        let mut keys = self.keys.lock().unwrap_or_else(|e| e.into_inner());
        self.rotate(&mut keys, now);
        let (id, rest) = ticket.split_at(8);
        let (nonce, rest) = rest.split_at(12);
        let (ct, tag) = rest.split_at(rest.len() - 16);
        for k in [&keys.current, &keys.previous].into_iter().flatten() {
            if k.id == id {
                let mut pt = ct.to_vec();
                return k.aead.open(nonce.try_into().unwrap(), &k.id, &mut pt, tag).then_some(pt);
            }
        }
        None
    }

    /// Forces a new key now (for tests and operators).
    pub fn rotate_now(&self, now_ms: u64) {
        let mut keys = self.keys.lock().unwrap_or_else(|e| e.into_inner());
        keys.previous = keys.current.take();
        keys.current = Some(Self::fresh(now_ms));
    }
}

/// Server configuration. A clone shares the certificates and the session ticket keys
/// (they sit behind `Arc`s), so a TCP listener and a QUIC listener can use one parsed
/// certificate with their own ALPN lists.
#[derive(Clone)]
pub struct ServerConfig {
    pub(crate) default_cert: Option<Arc<CertifiedKey>>,
    pub(crate) sni_certs: Vec<(String, Arc<CertifiedKey>)>,
    /// ALPN protocols in preference order (empty: ALPN is ignored).
    pub alpn: Vec<Vec<u8>>,
    pub client_auth: ClientAuth,
    pub suites: Vec<CipherSuite>,
    pub groups: Vec<NamedGroup>,
    /// Session tickets (None disables resumption).
    pub ticketer: Option<Arc<Ticketer>>,
    /// Ticket lifetime advertised to clients and enforced on resumption.
    pub ticket_lifetime_secs: u32,
    /// NewSessionTickets sent after each full handshake.
    pub ticket_count: u8,
    /// Reject clients whose SNI matches no configured name (unrecognized_name) instead of
    /// using the default certificate.
    pub strict_sni: bool,
    /// Largest handshake message accepted.
    pub max_handshake_message: usize,
    pub time: Arc<dyn TimeSource>,
    /// Lowest protocol version accepted (feature `tls12`; default TLS 1.2).
    #[cfg(feature = "tls12")]
    pub min_version: super::ProtocolVersion,
    /// Highest protocol version offered (feature `tls12`; default TLS 1.3, chosen whenever the
    /// client supports it).
    #[cfg(feature = "tls12")]
    pub max_version: super::ProtocolVersion,
    /// TLS 1.2 cipher suites in preference order (feature `tls12`).
    #[cfg(feature = "tls12")]
    pub suites12: Vec<super::tls12::Tls12Suite>,
    /// TLS 1.2 session-ID resumption for clients without ticket support (None disables it;
    /// tickets use `ticketer`).
    #[cfg(feature = "tls12")]
    pub session_ids: Option<Arc<super::tls12::SessionIdCache>>,
    /// The OCSP response stapled for clients that send `status_request` (feature
    /// `revocation`). The caller fetches and refreshes it; each handshake reads the current one.
    #[cfg(feature = "revocation")]
    pub ocsp_staple: Option<crate::revocation::StapleSource>,
    /// Revocation checks of client certificates (feature `revocation`): CRLs and online OCSP.
    #[cfg(feature = "revocation")]
    pub client_revocation: Option<crate::revocation::RevocationPolicy>,
}

impl std::fmt::Debug for ServerConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ServerConfig").field("alpn", &self.alpn).field("suites", &self.suites).field("groups", &self.groups).finish()
    }
}

impl ServerConfig {
    /// Accept TLS 1.3 only. Without the `tls12` feature that is already the only version, so
    /// this is a no-op; with it, it raises `min_version` to TLS 1.3. Lets code that must never
    /// accept TLS 1.2 say so whatever features feature unification switched on.
    pub fn require_tls13(&mut self) {
        #[cfg(feature = "tls12")]
        {
            self.min_version = super::ProtocolVersion::Tls13;
        }
    }

    /// A configuration serving one certificate chain; tickets on, no client authentication.
    pub fn new(cert: CertifiedKey) -> ServerConfig {
        ServerConfig {
            default_cert: Some(Arc::new(cert)),
            sni_certs: Vec::new(),
            alpn: Vec::new(),
            client_auth: ClientAuth::None,
            suites: CipherSuite::default_order(),
            groups: NamedGroup::ALL.to_vec(),
            ticketer: Some(Arc::new(Ticketer::new(6 * 3600))),
            ticket_lifetime_secs: 6 * 3600,
            ticket_count: 1,
            strict_sni: false,
            max_handshake_message: 64 * 1024,
            time: Arc::new(SystemClock),
            #[cfg(feature = "tls12")]
            min_version: super::ProtocolVersion::Tls12,
            #[cfg(feature = "tls12")]
            max_version: super::ProtocolVersion::Tls13,
            #[cfg(feature = "tls12")]
            suites12: super::tls12::Tls12Suite::default_order(),
            #[cfg(feature = "tls12")]
            session_ids: Some(Arc::new(super::tls12::SessionIdCache::new(1024))),
            #[cfg(feature = "revocation")]
            ocsp_staple: None,
            #[cfg(feature = "revocation")]
            client_revocation: None,
        }
    }

    /// From PEM certificate chain and key.
    pub fn from_pem(cert_pem: &[u8], key_pem: &[u8]) -> Result<ServerConfig> {
        Ok(ServerConfig::new(CertifiedKey::from_pem(cert_pem, key_pem)?))
    }

    /// Adds a certificate selected by SNI for every DNS name in its leaf (wildcards included).
    pub fn add_sni_cert(&mut self, cert: CertifiedKey) {
        let cert = Arc::new(cert);
        for n in cert.names() {
            self.sni_certs.push((n.clone(), cert.clone()));
        }
    }

    pub fn with_alpn(mut self, protocols: &[&[u8]]) -> ServerConfig {
        self.alpn = protocols.iter().map(|p| p.to_vec()).collect();
        self
    }

    pub(crate) fn resolve(&self, sni: Option<&str>) -> Option<Arc<CertifiedKey>> {
        if let Some(name) = sni {
            if let Some((_, c)) = self.sni_certs.iter().find(|(p, _)| crate::x509::dns_name_matches(p, name)) {
                return Some(c.clone());
            }
            if self.strict_sni && !self.sni_certs.is_empty() {
                return None;
            }
        }
        self.default_cert.clone()
    }
}

/// A resumable session remembered by a client.
#[cfg(feature = "client")]
#[derive(Clone, Debug)]
pub(crate) struct StoredSession {
    pub suite: CipherSuite,
    pub psk: Vec<u8>,
    pub ticket: Vec<u8>,
    pub age_add: u32,
    pub received_ms: u64,
    pub lifetime_secs: u32,
    pub alpn: Option<Vec<u8>>,
}

/// The client's session store: up to `per_server` tickets per server name, each used once.
#[cfg(feature = "client")]
pub struct SessionCache {
    map: Mutex<HashMap<String, VecDeque<StoredSession>>>,
    #[cfg(feature = "tls12")]
    map12: Mutex<HashMap<String, super::tls12::ClientSession12>>,
    max_servers: usize,
    per_server: usize,
}

#[cfg(feature = "client")]
impl std::fmt::Debug for SessionCache {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "SessionCache({} servers)", self.map.lock().map(|m| m.len()).unwrap_or(0))
    }
}

#[cfg(feature = "client")]
impl SessionCache {
    pub fn new(max_servers: usize) -> SessionCache {
        SessionCache {
            map: Mutex::new(HashMap::new()),
            #[cfg(feature = "tls12")]
            map12: Mutex::new(HashMap::new()),
            max_servers: max_servers.max(1),
            per_server: 4,
        }
    }

    /// Stores a TLS 1.2 session (one per server name; a newer one replaces it).
    #[cfg(feature = "tls12")]
    pub(crate) fn put12(&self, server: &str, s: super::tls12::ClientSession12) {
        let mut m = self.map12.lock().unwrap_or_else(|e| e.into_inner());
        if !m.contains_key(server) && m.len() >= self.max_servers {
            if let Some(k) = m.keys().next().cloned() {
                m.remove(&k);
            }
        }
        m.insert(server.to_string(), s);
    }

    /// The TLS 1.2 session for `server`, if still valid (it stays cached: TLS 1.2 tickets and
    /// session IDs may be reused, unlike TLS 1.3 tickets).
    #[cfg(feature = "tls12")]
    pub(crate) fn get12(&self, server: &str, now: u64) -> Option<super::tls12::ClientSession12> {
        let mut m = self.map12.lock().unwrap_or_else(|e| e.into_inner());
        match m.get(server) {
            Some(s) if now < s.received_ms + s.lifetime_secs as u64 * 1000 => Some(s.clone()),
            Some(_) => {
                m.remove(server);
                None
            }
            None => None,
        }
    }


    pub(crate) fn put(&self, server: &str, s: StoredSession) {
        let mut m = self.map.lock().unwrap_or_else(|e| e.into_inner());
        if !m.contains_key(server) && m.len() >= self.max_servers {
            if let Some(k) = m.keys().next().cloned() {
                m.remove(&k);
            }
        }
        let q = m.entry(server.to_string()).or_default();
        if q.len() >= self.per_server {
            q.pop_front();
        }
        q.push_back(s);
    }

    pub(crate) fn take(&self, server: &str, now: u64) -> Option<StoredSession> {
        let mut m = self.map.lock().unwrap_or_else(|e| e.into_inner());
        let q = m.get_mut(server)?;
        while let Some(s) = q.pop_back() {
            if now < s.received_ms + s.lifetime_secs as u64 * 1000 {
                return Some(s);
            }
        }
        None
    }

    /// Number of stored tickets for `server`.
    pub fn len_for(&self, server: &str) -> usize {
        self.map.lock().map(|m| m.get(server).map_or(0, |q| q.len())).unwrap_or(0)
    }
}

/// Client configuration.
#[cfg(feature = "client")]
pub struct ClientConfig {
    /// Trust anchors for server certificates. Verification cannot be turned off; to trust a
    /// self-signed server, add its certificate here.
    pub roots: RootStore,
    pub alpn: Vec<Vec<u8>>,
    pub suites: Vec<CipherSuite>,
    /// Groups in preference order; the first gets a key share in the ClientHello.
    pub groups: Vec<NamedGroup>,
    /// A certificate for servers that request one.
    pub client_cert: Option<CertifiedKey>,
    /// Session resumption (None disables it).
    pub sessions: Option<Arc<SessionCache>>,
    /// Send the server_name extension.
    pub enable_sni: bool,
    pub max_handshake_message: usize,
    pub time: Arc<dyn TimeSource>,
    /// Lowest protocol version offered (feature `tls12`; default TLS 1.2).
    #[cfg(feature = "tls12")]
    pub min_version: super::ProtocolVersion,
    /// Highest protocol version offered (feature `tls12`; default TLS 1.3).
    #[cfg(feature = "tls12")]
    pub max_version: super::ProtocolVersion,
    /// TLS 1.2 cipher suites in preference order (feature `tls12`).
    #[cfg(feature = "tls12")]
    pub suites12: Vec<super::tls12::Tls12Suite>,
    /// Revocation checks of the server certificate (feature `revocation`): OCSP stapling
    /// (`status_request`), CRLs and online OCSP. None checks nothing.
    #[cfg(feature = "revocation")]
    pub revocation: Option<crate::revocation::RevocationPolicy>,
}

#[cfg(feature = "client")]
impl std::fmt::Debug for ClientConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ClientConfig").field("roots", &self.roots).field("alpn", &self.alpn).finish()
    }
}

#[cfg(feature = "client")]
impl ClientConfig {
    pub fn new(roots: RootStore) -> ClientConfig {
        ClientConfig {
            roots,
            alpn: Vec::new(),
            suites: CipherSuite::ALL.to_vec(),
            groups: NamedGroup::ALL.to_vec(),
            client_cert: None,
            sessions: Some(Arc::new(SessionCache::new(256))),
            enable_sni: true,
            max_handshake_message: 64 * 1024,
            time: Arc::new(SystemClock),
            #[cfg(feature = "tls12")]
            min_version: super::ProtocolVersion::Tls12,
            #[cfg(feature = "tls12")]
            max_version: super::ProtocolVersion::Tls13,
            #[cfg(feature = "tls12")]
            suites12: super::tls12::Tls12Suite::default_order(),
            #[cfg(feature = "revocation")]
            revocation: None,
        }
    }

    pub fn with_alpn(mut self, protocols: &[&[u8]]) -> ClientConfig {
        self.alpn = protocols.iter().map(|p| p.to_vec()).collect();
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Bug 13: the leaf is parsed once, in CertifiedKey::new; names() and SNI use the result,
    // and a cloned ServerConfig shares the parsed certificate instead of copying it.
    #[test]
    fn certificate_parsed_once_and_shared_by_clones() {
        let ss = crate::certgen::self_signed_with_sans(&["a.example", "*.b.example"], 30);
        let ck = CertifiedKey::new(vec![ss.cert_der.clone()], ss.key.clone()).unwrap();
        assert_eq!(ck.names(), ["a.example".to_string(), "*.b.example".to_string()]);
        let mut cfg = ServerConfig::new(ck.clone());
        cfg.add_sni_cert(ck);
        assert_eq!(cfg.sni_certs.len(), 2);
        assert!(cfg.resolve(Some("x.b.example")).is_some());
        let h3 = cfg.clone().with_alpn(&[b"h3"]);
        assert!(Arc::ptr_eq(cfg.default_cert.as_ref().unwrap(), h3.default_cert.as_ref().unwrap()));
        assert!(Arc::ptr_eq(cfg.ticketer.as_ref().unwrap(), h3.ticketer.as_ref().unwrap()));
        assert!(cfg.alpn.is_empty() && h3.alpn == [b"h3".to_vec()]);
    }
}