Skip to main content

net_io/
tls.rs

1//! The TLS seam: traits a TLS engine implements in its own crate.
2//!
3//! net-io carries no TLS code. The seam is in place and sans-IO: ciphertext is
4//! decrypted inside the connection's own read buffer and plaintext is encrypted
5//! straight into net-io's output buffer. The server integration arrives in
6//! `0.4.0` behind the `tls` feature; the traits exist in every build.
7
8use std::fmt;
9
10use crate::info::ConnectionInfo;
11
12/// Creates one [`TlsSession`] per admitted connection.
13///
14/// # Examples
15///
16/// ```
17/// use net_io::{ConnectionInfo, NoTls, TlsAcceptor};
18/// let info = ConnectionInfo::for_testing("127.0.0.1:1".parse().unwrap());
19/// assert!(NoTls.session(&info).is_err());
20/// ```
21pub trait TlsAcceptor: Send + Sync + 'static {
22    /// The per-connection session type.
23    type Session: TlsSession;
24
25    /// Called once per admitted connection, after PROXY and readmission, before any TLS byte is read.
26    ///
27    /// # Errors
28    ///
29    /// A [`TlsError`] refuses the connection (for example an acceptor at capacity).
30    fn session(&self, info: &ConnectionInfo) -> Result<Self::Session, TlsError>;
31}
32
33/// One connection's TLS state machine. Never blocks, never does IO.
34///
35/// See `docs/API.md` (TLS seam) for how the server drives it.
36pub trait TlsSession: Send + 'static {
37    /// Ciphertext is in `input`; free space for records to send is `output`.
38    ///
39    /// # Errors
40    ///
41    /// A [`TlsError`]; `TlsFailure::HelloRefused` closes the connection with
42    /// `CloseReason::HelloRefused`, anything else with `TlsFailed`.
43    fn step<'i>(
44        &mut self,
45        input: &'i mut [u8],
46        output: &mut [u8],
47    ) -> Result<TlsProgress<'i>, TlsError>;
48
49    /// Encrypts `plaintext` into `output`: all records or none.
50    ///
51    /// # Errors
52    ///
53    /// `TlsFailure::OutputFull` when `output` cannot hold every record.
54    fn encrypt(&mut self, plaintext: &[u8], output: &mut [u8]) -> Result<usize, TlsError>;
55
56    /// Writes `close_notify` into `output`.
57    ///
58    /// # Errors
59    ///
60    /// `TlsFailure::OutputFull` or `TlsFailure::State`.
61    fn close(&mut self, output: &mut [u8]) -> Result<usize, TlsError>;
62
63    /// The peer's transport closed: was the TLS stream ended cleanly?
64    fn on_transport_closed(&mut self) -> TlsCloseKind;
65
66    /// SNI, ALPN, version, and cipher suite; `Some` after the handshake.
67    fn info(&self) -> Option<TlsInfo>;
68
69    /// The smallest input buffer the session needs now.
70    fn input_capacity_required(&self) -> usize;
71}
72
73/// What one [`TlsSession::step`] did.
74#[must_use]
75#[derive(Debug)]
76pub struct TlsProgress<'i> {
77    /// Input bytes the engine consumed.
78    pub consumed: usize,
79    /// Bytes the engine wrote at the start of `output`.
80    pub written: usize,
81    /// What the caller does next.
82    pub event: TlsEvent<'i>,
83}
84
85/// The next thing the driver does after a step.
86#[non_exhaustive]
87#[derive(Debug)]
88pub enum TlsEvent<'i> {
89    /// Read more ciphertext, append it after the unconsumed bytes, call `step` again.
90    NeedInput,
91    /// Send the `written` bytes at the start of `output`, all of them.
92    Transmit,
93    /// The handshake finished; `info()` is now `Some`.
94    HandshakeComplete,
95    /// Plaintext decrypted in place; call `step` again for more.
96    Data(&'i [u8]),
97    /// Not enough room in `output`; flush and call again.
98    OutputFull,
99    /// `close_notify` was received.
100    PeerClosed,
101    /// Both directions are closed.
102    Closed,
103}
104
105/// Whether a TLS stream ended with `close_notify`.
106///
107/// ```
108/// assert_ne!(net_io::TlsCloseKind::Clean, net_io::TlsCloseKind::Unclean);
109/// ```
110#[non_exhaustive]
111#[derive(Clone, Copy, Debug, PartialEq, Eq)]
112pub enum TlsCloseKind {
113    /// `close_notify` was seen.
114    Clean,
115    /// The transport closed without it.
116    Unclean,
117}
118
119/// What failed in a TLS engine.
120///
121/// ```
122/// assert_ne!(net_io::TlsFailure::Handshake, net_io::TlsFailure::HelloRefused);
123/// ```
124#[non_exhaustive]
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub enum TlsFailure {
127    /// The handshake failed.
128    Handshake,
129    /// The engine's hello hook refused the ClientHello.
130    HelloRefused,
131    /// The acceptor is at capacity.
132    Capacity,
133    /// The peer broke the protocol.
134    Protocol,
135    /// The output buffer is too small.
136    OutputFull,
137    /// The call is not valid in the session's state.
138    State,
139}
140
141/// A TLS engine error: codes only, never secret material.
142///
143/// ```
144/// use net_io::{TlsError, TlsFailure};
145/// let e = TlsError::new(TlsFailure::HelloRefused, 3, None);
146/// assert_eq!(e.kind, TlsFailure::HelloRefused);
147/// ```
148#[non_exhaustive]
149#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub struct TlsError {
151    /// What failed.
152    pub kind: TlsFailure,
153    /// The engine's own code.
154    pub code: u16,
155    /// The TLS alert sent or received, if any.
156    pub alert: Option<u8>,
157}
158
159impl TlsError {
160    /// Builds an error.
161    #[must_use]
162    pub const fn new(kind: TlsFailure, code: u16, alert: Option<u8>) -> TlsError {
163        TlsError { kind, code, alert }
164    }
165}
166
167impl fmt::Display for TlsError {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        write!(f, "{:?} (engine code {}", self.kind, self.code)?;
170        if let Some(alert) = self.alert {
171            write!(f, ", alert {alert}")?;
172        }
173        f.write_str(")")
174    }
175}
176
177impl std::error::Error for TlsError {}
178
179/// TLS facts after the handshake, in fixed arrays.
180///
181/// ```
182/// let info = net_io::TlsInfo::new(Some("example.com"), Some(b"h2"), 0x0304, 0x1301).unwrap();
183/// assert_eq!(info.sni(), Some("example.com"));
184/// assert!(net_io::TlsInfo::new(Some(&"a".repeat(256)), None, 0, 0).is_none());
185/// assert_eq!(info.peer_spki_sha256(), None);
186/// let mutual = info.with_peer_spki_sha256([7; 32]);
187/// assert_eq!(mutual.peer_spki_sha256(), Some(&[7; 32]));
188/// ```
189#[non_exhaustive]
190#[derive(Clone, Copy)]
191pub struct TlsInfo {
192    sni: [u8; 255],
193    sni_len: u8,
194    alpn: [u8; 32],
195    alpn_len: u8,
196    version: u16,
197    cipher_suite: u16,
198    peer_spki: Option<[u8; 32]>,
199}
200
201impl TlsInfo {
202    /// Builds the facts; `None` if the SNI is longer than 255 bytes or the ALPN longer than 32.
203    #[must_use]
204    pub fn new(
205        sni: Option<&str>,
206        alpn: Option<&[u8]>,
207        version: u16,
208        cipher_suite: u16,
209    ) -> Option<TlsInfo> {
210        let sni = sni.unwrap_or("").as_bytes();
211        let alpn = alpn.unwrap_or(&[]);
212        if sni.len() > 255 || alpn.len() > 32 {
213            return None;
214        }
215        let mut info = TlsInfo {
216            sni: [0; 255],
217            sni_len: u8::try_from(sni.len()).ok()?,
218            alpn: [0; 32],
219            alpn_len: u8::try_from(alpn.len()).ok()?,
220            version,
221            cipher_suite,
222            peer_spki: None,
223        };
224        info.sni[..sni.len()].copy_from_slice(sni);
225        info.alpn[..alpn.len()].copy_from_slice(alpn);
226        Some(info)
227    }
228
229    /// The server name the client asked for.
230    #[must_use]
231    pub fn sni(&self) -> Option<&str> {
232        if self.sni_len == 0 {
233            return None;
234        }
235        std::str::from_utf8(&self.sni[..usize::from(self.sni_len)]).ok()
236    }
237
238    /// The negotiated application protocol.
239    #[must_use]
240    pub fn alpn(&self) -> Option<&[u8]> {
241        (self.alpn_len > 0).then(|| &self.alpn[..usize::from(self.alpn_len)])
242    }
243
244    /// The protocol version code (for example `0x0304` for TLS 1.3).
245    #[must_use]
246    pub fn version(&self) -> u16 {
247        self.version
248    }
249
250    /// The cipher suite code.
251    #[must_use]
252    pub fn cipher_suite(&self) -> u16 {
253        self.cipher_suite
254    }
255
256    /// The facts with the SHA-256 of the client certificate's public key
257    /// (its DER `SubjectPublicKeyInfo`). The engine sets it only for a client
258    /// certificate it verified (the chain, or a pin), never from unverified bytes.
259    #[must_use]
260    pub fn with_peer_spki_sha256(mut self, hash: [u8; 32]) -> TlsInfo {
261        self.peer_spki = Some(hash);
262        self
263    }
264
265    /// The SHA-256 of the verified client certificate's public key, for mapping a
266    /// mutual-TLS peer to a principal; `None` without a client certificate. It
267    /// stays the same when the certificate is reissued with the same key.
268    #[must_use]
269    pub fn peer_spki_sha256(&self) -> Option<&[u8; 32]> {
270        self.peer_spki.as_ref()
271    }
272}
273
274impl fmt::Debug for TlsInfo {
275    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
276        f.debug_struct("TlsInfo")
277            .field("sni", &self.sni())
278            .field("alpn", &self.alpn().map(String::from_utf8_lossy))
279            .field("version", &format_args!("{:#06x}", self.version))
280            .field("cipher_suite", &format_args!("{:#06x}", self.cipher_suite))
281            .field("peer_spki_sha256", &self.peer_spki.map(Hex))
282            .finish()
283    }
284}
285
286/// Bytes printed as lowercase hex.
287struct Hex([u8; 32]);
288
289impl fmt::Debug for Hex {
290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291        self.0.iter().try_for_each(|b| write!(f, "{b:02x}"))
292    }
293}
294
295/// The builder's default acceptor: no listener may enable TLS with it.
296///
297/// ```
298/// use net_io::{ConnectionInfo, NoTls, TlsAcceptor};
299/// let info = ConnectionInfo::for_testing("127.0.0.1:1".parse().unwrap());
300/// assert!(NoTls.session(&info).is_err());
301/// ```
302#[derive(Clone, Copy, Debug, Default)]
303pub struct NoTls;
304
305/// An acceptor behind a pointer: sessions come back boxed.
306#[cfg_attr(not(feature = "tls"), allow(dead_code))]
307pub(crate) trait ErasedAcceptor: Send + Sync {
308    fn session_boxed(&self, info: &ConnectionInfo) -> Result<Box<dyn TlsSession>, TlsError>;
309}
310
311impl<A: TlsAcceptor> ErasedAcceptor for A {
312    fn session_boxed(&self, info: &ConnectionInfo) -> Result<Box<dyn TlsSession>, TlsError> {
313        match crate::gate::guarded(|| self.session(info)) {
314            Some(Ok(s)) => Ok(Box::new(Guarded {
315                inner: Box::new(s),
316                poisoned: false,
317            })),
318            Some(Err(e)) => Err(e),
319            None => Err(PANICKED),
320        }
321    }
322}
323
324/// The error a panicking engine call becomes.
325const PANICKED: TlsError = TlsError::new(TlsFailure::State, u16::MAX, None);
326
327/// An engine behind a panic boundary: a panic in any call becomes [`PANICKED`] and
328/// every later call fails the same way, so the connection closes `TlsFailed` through
329/// the normal close path and its worker, slots, and ticket survive. The engine parses
330/// the most hostile bytes a connection carries; this keeps one engine bug from
331/// taking a worker with it. No cost unless a panic unwinds.
332struct Guarded {
333    inner: Box<dyn TlsSession>,
334    poisoned: bool,
335}
336
337impl Guarded {
338    fn call<R>(
339        &mut self,
340        f: impl FnOnce(&mut dyn TlsSession) -> Result<R, TlsError>,
341    ) -> Result<R, TlsError> {
342        if self.poisoned {
343            return Err(PANICKED);
344        }
345        let inner = &mut *self.inner;
346        match crate::gate::guarded(|| f(inner)) {
347            Some(r) => r,
348            None => {
349                self.poisoned = true;
350                Err(PANICKED)
351            }
352        }
353    }
354}
355
356impl TlsSession for Guarded {
357    fn step<'i>(
358        &mut self,
359        input: &'i mut [u8],
360        output: &mut [u8],
361    ) -> Result<TlsProgress<'i>, TlsError> {
362        if self.poisoned {
363            return Err(PANICKED);
364        }
365        let inner = &mut *self.inner;
366        match crate::gate::guarded(move || inner.step(input, output)) {
367            Some(r) => r,
368            None => {
369                self.poisoned = true;
370                Err(PANICKED)
371            }
372        }
373    }
374
375    fn encrypt(&mut self, plaintext: &[u8], output: &mut [u8]) -> Result<usize, TlsError> {
376        self.call(|s| s.encrypt(plaintext, output))
377    }
378
379    fn close(&mut self, output: &mut [u8]) -> Result<usize, TlsError> {
380        self.call(|s| s.close(output))
381    }
382
383    fn on_transport_closed(&mut self) -> TlsCloseKind {
384        self.call(|s| Ok(s.on_transport_closed()))
385            .unwrap_or(TlsCloseKind::Unclean)
386    }
387
388    fn info(&self) -> Option<TlsInfo> {
389        if self.poisoned {
390            return None;
391        }
392        crate::gate::guarded(|| self.inner.info()).flatten()
393    }
394
395    fn input_capacity_required(&self) -> usize {
396        if self.poisoned {
397            return 0;
398        }
399        crate::gate::guarded(|| self.inner.input_capacity_required()).unwrap_or(0)
400    }
401}
402
403/// The session type of [`NoTls`]; it has no values.
404#[derive(Debug)]
405pub enum NoTlsSession {}
406
407impl TlsAcceptor for NoTls {
408    type Session = NoTlsSession;
409    fn session(&self, _info: &ConnectionInfo) -> Result<NoTlsSession, TlsError> {
410        Err(TlsError::new(TlsFailure::State, 0, None))
411    }
412}
413
414impl TlsSession for NoTlsSession {
415    fn step<'i>(
416        &mut self,
417        _input: &'i mut [u8],
418        _output: &mut [u8],
419    ) -> Result<TlsProgress<'i>, TlsError> {
420        match *self {}
421    }
422    fn encrypt(&mut self, _plaintext: &[u8], _output: &mut [u8]) -> Result<usize, TlsError> {
423        match *self {}
424    }
425    fn close(&mut self, _output: &mut [u8]) -> Result<usize, TlsError> {
426        match *self {}
427    }
428    fn on_transport_closed(&mut self) -> TlsCloseKind {
429        match *self {}
430    }
431    fn info(&self) -> Option<TlsInfo> {
432        match *self {}
433    }
434    fn input_capacity_required(&self) -> usize {
435        match *self {}
436    }
437}