Skip to main content

coqui_peer_tls/
stream.rs

1use alloc::sync::Arc;
2use core::net::SocketAddr;
3use core::time::Duration;
4use std::io::{self, Read, Write};
5use std::net::TcpStream;
6
7use rustls::pki_types::{CertificateDer, ServerName};
8use rustls::{ClientConfig, ClientConnection, ServerConfig, ServerConnection, StreamOwned};
9
10use crate::error::{PeerError, Refusal};
11use crate::identity::PeerIdentity;
12use crate::source::scoped;
13use coqui_peer::{PeerId, ReadTimeout, WriteTimeout};
14
15/// The server name [`dial`] and [`TlsHandshake::client`](crate::TlsHandshake::client) send,
16/// and the subjectAltName of generated identities. Pinned trust is by fingerprint, so the name
17/// carries no meaning there; [`Roots`](crate::Roots) check the name, so dial a server they
18/// verify with [`dial_named`].
19pub const SERVER_NAME: &str = "coqui-peer.invalid";
20
21/// [`SERVER_NAME`] as the name rustls takes, for a host that dials with a connector of its own
22/// (rustls, tokio-rustls, quinn) and trusts by pins.
23pub fn default_server_name() -> ServerName<'static> {
24    ServerName::try_from(SERVER_NAME).expect("SERVER_NAME is a valid DNS name")
25}
26
27pub(crate) fn identity_of(
28    certificates: Option<&[CertificateDer<'static>]>,
29) -> Result<PeerIdentity, PeerError> {
30    let certificate = certificates
31        .and_then(<[_]>::first)
32        .ok_or(PeerError::Certificate)?;
33    Ok(PeerIdentity {
34        fingerprint: PeerId::of(certificate.as_ref()),
35        certificate: certificate.as_ref().to_vec(),
36    })
37}
38
39/// Dials a peer over `io`, completing the handshake before returning.
40///
41/// Returns the encrypted stream and the verified peer. `io` is any blocking byte stream. The
42/// server name sent is [`SERVER_NAME`]; [`dial_named`] sends another.
43///
44/// # Errors
45///
46/// [`PeerError::Io`] when the handshake fails, including a refused peer certificate;
47/// [`PeerError::refusal`] says why this side refused one.
48pub fn dial<S: Read + Write>(
49    config: Arc<ClientConfig>,
50    io: S,
51) -> Result<(StreamOwned<ClientConnection, S>, PeerIdentity), PeerError> {
52    dial_named(config, default_server_name(), io)
53}
54
55/// [`dial`] sending `name` as the server name: the host the client dialled, for a server
56/// verified by [`Roots`](crate::Roots), which check that its certificate is for that name
57/// (a DNS name, or an IP address the certificate names). Pinned trust ignores the name.
58///
59/// The returned peer's fingerprint is the server's leaf certificate's, however it was
60/// verified.
61///
62/// # Errors
63///
64/// [`PeerError::Io`] when the handshake fails, including a refused server certificate;
65/// [`PeerError::refusal`] says why this side refused one.
66pub fn dial_named<S: Read + Write>(
67    config: Arc<ClientConfig>,
68    name: ServerName<'static>,
69    mut io: S,
70) -> Result<(StreamOwned<ClientConnection, S>, PeerIdentity), PeerError> {
71    let mut connection = ClientConnection::new(config, name).map_err(|_| PeerError::Tls)?;
72    while connection.is_handshaking() {
73        connection.complete_io(&mut io).map_err(PeerError::Io)?;
74    }
75    let peer = identity_of(connection.peer_certificates())?;
76    Ok((StreamOwned::new(connection, io), peer))
77}
78
79/// A stream that can name the remote address it is connected to.
80///
81/// [`accept`] uses it to record where a refused peer came from. A stream without an address,
82/// or one that is not TCP, is accepted wrapped in an [`Addressed`].
83pub trait PeerAddr {
84    /// The remote address, when known.
85    fn peer_addr(&self) -> Option<SocketAddr>;
86
87    /// The local address the connection arrived at, when known: a policy's access control
88    /// list reads it for rules that name a destination or a port. `None` unless implemented.
89    fn local_addr(&self) -> Option<SocketAddr> {
90        None
91    }
92}
93
94impl PeerAddr for TcpStream {
95    fn peer_addr(&self) -> Option<SocketAddr> {
96        TcpStream::peer_addr(self).ok()
97    }
98
99    fn local_addr(&self) -> Option<SocketAddr> {
100        TcpStream::local_addr(self).ok()
101    }
102}
103
104/// A stream with the addresses of its connection given, for a stream that cannot name them
105/// itself (a pipe, a tunnel, a test double): [`accept`] and the pairing functions read them
106/// through [`PeerAddr`], so they accept it as they accept a TCP stream.
107///
108/// It reads, writes and times out as the stream does ([`Read`], [`Write`],
109/// `ReadTimeout`, `WriteTimeout`, and with the `tokio` feature `AsyncRead` and `AsyncWrite`). The
110/// stream a function returns holds the wrapper: [`into_inner`](Self::into_inner) takes the
111/// stream back.
112#[derive(Debug)]
113pub struct Addressed<S> {
114    io: S,
115    source: SocketAddr,
116    local: Option<SocketAddr>,
117}
118
119impl<S> Addressed<S> {
120    /// `io` as a connection from `source`, with no local address.
121    pub fn new(io: S, source: SocketAddr) -> Self {
122        Self {
123            io,
124            source,
125            local: None,
126        }
127    }
128
129    /// The local address the connection arrived at, which a policy's access control list reads
130    /// for rules that name a destination or a port.
131    pub fn local(mut self, local: SocketAddr) -> Self {
132        self.local = Some(local);
133        self
134    }
135
136    /// The wrapped stream.
137    pub fn get_ref(&self) -> &S {
138        &self.io
139    }
140
141    /// The wrapped stream, mutably.
142    pub fn get_mut(&mut self) -> &mut S {
143        &mut self.io
144    }
145
146    /// The wrapped stream.
147    pub fn into_inner(self) -> S {
148        self.io
149    }
150}
151
152impl<S> PeerAddr for Addressed<S> {
153    fn peer_addr(&self) -> Option<SocketAddr> {
154        Some(self.source)
155    }
156
157    fn local_addr(&self) -> Option<SocketAddr> {
158        self.local
159    }
160}
161
162impl<S: Read> Read for Addressed<S> {
163    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
164        self.io.read(buffer)
165    }
166}
167
168impl<S: Write> Write for Addressed<S> {
169    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
170        self.io.write(buffer)
171    }
172
173    fn flush(&mut self) -> io::Result<()> {
174        self.io.flush()
175    }
176}
177
178impl<S: ReadTimeout> ReadTimeout for Addressed<S> {
179    fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
180        self.io.set_read_timeout(timeout)
181    }
182}
183
184impl<S: WriteTimeout> WriteTimeout for Addressed<S> {
185    fn set_write_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
186        self.io.set_write_timeout(timeout)
187    }
188}
189
190/// The error of a handshake that failed: the refusal the address check recorded, as a
191/// verifier's refusal is carried, or the transport's error.
192pub(crate) fn handshake_error(error: io::Error, refused: Option<Refusal>) -> PeerError {
193    match refused {
194        Some(refusal) => PeerError::Io(io::Error::new(
195            io::ErrorKind::PermissionDenied,
196            refusal.into_rustls(),
197        )),
198        None => PeerError::Io(error),
199    }
200}
201
202/// Accepts a peer over `io`, completing the handshake before returning.
203///
204/// A client whose certificate the configured [`Trust`](crate::Trust) refuses fails the
205/// handshake; when the trust is a store-backed pin set and the client proved it holds the
206/// certificate's key, it is recorded as waiting under the address of `io`.
207///
208/// It returns a verified client, so it needs one: with a server built with
209/// [`ClientAuth::None`](crate::ClientAuth::None) it fails
210/// with [`PeerError::Certificate`] after the handshake. Accept those with
211/// [`TlsHandshake::finish_unauthenticated`](crate::TlsHandshake::finish_unauthenticated), or
212/// with rustls's or tokio-rustls's own acceptor, which need nothing from this crate.
213///
214/// # Errors
215///
216/// [`PeerError::Io`] when the handshake fails; [`PeerError::refusal`] says why this side
217/// refused the peer certificate, when it did.
218pub fn accept<S: Read + Write + PeerAddr>(
219    config: Arc<ServerConfig>,
220    io: S,
221) -> Result<(StreamOwned<ServerConnection, S>, PeerIdentity), PeerError> {
222    let (source, local) = (io.peer_addr(), io.local_addr());
223    accept_from_as(config, io, source, local)
224}
225
226pub(crate) fn accept_from_as<S: Read + Write>(
227    config: Arc<ServerConfig>,
228    mut io: S,
229    source: Option<SocketAddr>,
230    local: Option<SocketAddr>,
231) -> Result<(StreamOwned<ServerConnection, S>, PeerIdentity), PeerError> {
232    let mut connection = ServerConnection::new(config).map_err(|_| PeerError::Tls)?;
233    let (handshake, refused) = scoped(source, local, || {
234        while connection.is_handshaking() {
235            connection.complete_io(&mut io)?;
236        }
237        Ok::<(), io::Error>(())
238    });
239    handshake.map_err(|error| handshake_error(error, refused))?;
240    let peer = identity_of(connection.peer_certificates())?;
241    Ok((StreamOwned::new(connection, io), peer))
242}