Skip to main content

coqui_peer_tls/
handshake.rs

1use alloc::sync::Arc;
2use core::net::SocketAddr;
3use std::io::Cursor;
4
5use coqui_peer::{Established, Framing, Handshake, Method};
6use rustls::pki_types::ServerName;
7use rustls::{ClientConfig, ClientConnection, Connection, ServerConfig, ServerConnection};
8
9use crate::certificate::key_of_presented;
10use crate::error::PeerError;
11use crate::identity::PeerIdentity;
12use crate::source::scoped;
13use crate::stream::handshake_error;
14use crate::stream::{default_server_name, identity_of};
15
16/// The TLS method: client and server configurations, each optional, that start handshakes.
17///
18/// ```no_run
19/// # fn demo(client: rustls::ClientConfig, server: rustls::ServerConfig) {
20/// let method = coqui_peer_tls::Tls::new()
21///     .client(std::sync::Arc::new(client))
22///     .server(std::sync::Arc::new(server));
23/// # let _ = method;
24/// # }
25/// ```
26#[derive(Debug, Clone, Default)]
27pub struct Tls {
28    client: Option<Arc<ClientConfig>>,
29    server: Option<Arc<ServerConfig>>,
30}
31
32impl Tls {
33    /// A method that can neither dial nor accept until configured.
34    pub fn new() -> Self {
35        Self::default()
36    }
37
38    /// This method able to dial with `config` (see [`ClientBuilder`](crate::ClientBuilder)).
39    #[must_use]
40    pub fn client(mut self, config: Arc<ClientConfig>) -> Self {
41        self.client = Some(config);
42        self
43    }
44
45    /// This method able to accept with `config` (see [`ServerBuilder`](crate::ServerBuilder)).
46    #[must_use]
47    pub fn server(mut self, config: Arc<ServerConfig>) -> Self {
48        self.server = Some(config);
49        self
50    }
51}
52
53impl Method for Tls {
54    type Handshake = TlsHandshake;
55
56    fn name(&self) -> &'static str {
57        crate::METHOD
58    }
59
60    fn initiate(&self) -> Result<TlsHandshake, PeerError> {
61        let config = self.client.clone().ok_or(PeerError::Unsupported)?;
62        TlsHandshake::client(config)
63    }
64
65    fn respond(&self, source: Option<SocketAddr>) -> Result<TlsHandshake, PeerError> {
66        let config = self.server.clone().ok_or(PeerError::Unsupported)?;
67        TlsHandshake::server(config, source)
68    }
69}
70
71/// One TLS handshake, driven by the caller: rustls's own sans-IO connection.
72///
73/// A server records a refused, key-proven client as waiting under the `source` it was given,
74/// exactly as [`accept`](crate::accept) does. After [`finish`](Handshake::finish) the
75/// [`session`](Established::session) is the finished [`rustls::Connection`], which keeps any
76/// application data that arrived with the last handshake bytes.
77#[derive(Debug)]
78pub struct TlsHandshake {
79    connection: Connection,
80    source: Option<SocketAddr>,
81    local: Option<SocketAddr>,
82}
83
84impl TlsHandshake {
85    /// A handshake as the dialing side, sending [`SERVER_NAME`](crate::SERVER_NAME) as the
86    /// server name.
87    ///
88    /// # Errors
89    ///
90    /// [`PeerError::Tls`] when the connection cannot be created.
91    pub fn client(config: Arc<ClientConfig>) -> Result<Self, PeerError> {
92        Self::client_named(config, default_server_name())
93    }
94
95    /// A handshake as the dialing side, sending `name` as the server name: the host dialled,
96    /// for a server verified by [`Roots`](crate::Roots). [`Established::peer`] is the
97    /// server's leaf certificate's fingerprint, however it was verified.
98    ///
99    /// # Errors
100    ///
101    /// [`PeerError::Tls`] when the connection cannot be created.
102    pub fn client_named(
103        config: Arc<ClientConfig>,
104        name: ServerName<'static>,
105    ) -> Result<Self, PeerError> {
106        let connection = ClientConnection::new(config, name).map_err(|_| PeerError::Tls)?;
107        Ok(Self {
108            connection: connection.into(),
109            source: None,
110            local: None,
111        })
112    }
113
114    /// A handshake as the accepting side; `source` is where the peer connected from.
115    ///
116    /// # Errors
117    ///
118    /// [`PeerError::Tls`] when the connection cannot be created.
119    pub fn server(
120        config: Arc<ServerConfig>,
121        source: Option<SocketAddr>,
122    ) -> Result<Self, PeerError> {
123        let connection = ServerConnection::new(config).map_err(|_| PeerError::Tls)?;
124        Ok(Self {
125            connection: connection.into(),
126            source,
127            local: None,
128        })
129    }
130
131    /// This handshake knowing the local address the connection arrived at, which a policy's
132    /// access control list reads for rules that name a destination or a port. A server
133    /// handshake without one refuses a connection such a rule would decide
134    /// ([`Refusal::AddressUnknown`](crate::Refusal::AddressUnknown)).
135    #[must_use]
136    pub fn local(mut self, local: SocketAddr) -> Self {
137        self.local = Some(local);
138        self
139    }
140
141    /// Finishes a completed handshake whose peer may have presented no certificate: the
142    /// connection, and the peer's verified certificate when it sent one.
143    ///
144    /// A server built with [`ClientAuth::None`](crate::ClientAuth::None)
145    /// asks for none, so its peer is always `None` and [`Handshake::finish`], which needs a
146    /// peer, fails there. **`None` means the client is not authenticated**: the application
147    /// must authenticate it inside the connection before trusting it. Drive the handshake with
148    /// `coqui_peer::complete_stream` or `complete_messages`, then call this.
149    ///
150    /// # Errors
151    ///
152    /// [`PeerError::Tls`] when the handshake is not complete.
153    pub fn finish_unauthenticated(self) -> Result<(Connection, Option<PeerIdentity>), PeerError> {
154        if self.connection.is_handshaking() {
155            return Err(PeerError::Tls);
156        }
157        let peer = match self.connection.peer_certificates() {
158            Some(certificates) if !certificates.is_empty() => {
159                Some(identity_of(Some(certificates))?)
160            }
161            _ => None,
162        };
163        Ok((self.connection, peer))
164    }
165}
166
167impl Handshake for TlsHandshake {
168    type Output = Connection;
169    type Error = PeerError;
170
171    fn framing(&self) -> Framing {
172        Framing::Stream
173    }
174
175    fn receive(&mut self, input: &[u8]) -> Result<(), PeerError> {
176        let mut cursor = Cursor::new(input);
177        while usize::try_from(cursor.position()).unwrap_or(usize::MAX) < input.len() {
178            let read = self
179                .connection
180                .read_tls(&mut cursor)
181                .map_err(PeerError::Io)?;
182            let (processed, refused) = scoped(self.source, self.local, || {
183                self.connection.process_new_packets().map(|_| ())
184            });
185            processed.map_err(|error| {
186                handshake_error(
187                    std::io::Error::new(std::io::ErrorKind::InvalidData, error),
188                    refused,
189                )
190            })?;
191            if read == 0 {
192                return Err(PeerError::Tls);
193            }
194        }
195        Ok(())
196    }
197
198    fn transmit(&mut self) -> Result<Option<Vec<u8>>, PeerError> {
199        if !self.connection.wants_write() {
200            return Ok(None);
201        }
202        let mut out = Vec::new();
203        self.connection.write_tls(&mut out).map_err(PeerError::Io)?;
204        Ok((!out.is_empty()).then_some(out))
205    }
206
207    fn is_complete(&self) -> bool {
208        !self.connection.is_handshaking()
209    }
210
211    fn finish(self) -> Result<Established<Connection>, PeerError> {
212        if self.connection.is_handshaking() {
213            return Err(PeerError::Tls);
214        }
215        let peer = identity_of(self.connection.peer_certificates())?;
216        Ok(Established {
217            peer: peer.fingerprint,
218            key: Some(key_of_presented(&peer.certificate)?),
219            session: self.connection,
220        })
221    }
222}