Skip to main content

uas_cot/net/
tls.rs

1//! TLS streaming to a TAK Server (feature `tls`, rustls with the ring
2//! provider, no OpenSSL).
3
4use crate::Event;
5use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
6use rustls::client::WebPkiServerVerifier;
7use rustls::crypto::CryptoProvider;
8use rustls::pki_types::pem::PemObject;
9use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
10use rustls::{
11    CertificateError, ClientConfig, ClientConnection, DigitallySignedStruct, RootCertStore,
12};
13use rustls::{SignatureScheme, StreamOwned};
14use std::io::{self, Write};
15use std::net::{TcpStream, ToSocketAddrs};
16use std::path::Path;
17use std::sync::Arc;
18
19fn invalid(msg: impl std::fmt::Display) -> io::Error {
20    io::Error::new(io::ErrorKind::InvalidData, msg.to_string())
21}
22
23fn provider() -> Arc<CryptoProvider> {
24    Arc::new(rustls::crypto::ring::default_provider())
25}
26
27/// How to reach a TAK Server TLS streaming input (usually port 8089): the
28/// CA that signed the server certificate, and your client certificate and
29/// key. TAK Server requires the client certificate by default.
30///
31/// TAK hands out `.p12` files. Convert them to PEM once with OpenSSL (the
32/// default TAK password is often `atakatak`; OpenSSL 3 needs `-legacy` for
33/// the older encryption TAK uses):
34///
35/// ```text
36/// openssl pkcs12 -legacy -in truststore-root.p12 -nokeys -out ca.pem
37/// openssl pkcs12 -legacy -in user.p12 -clcerts -nokeys -out user.pem
38/// openssl pkcs12 -legacy -in user.p12 -nocerts -nodes -out user.key
39/// ```
40///
41/// For anything else (PKCS#12 directly, platform trust stores, custom
42/// verification) build a [`rustls::ClientConfig`] yourself and use
43/// [`TlsConfig::from_rustls`].
44#[derive(Clone, Debug)]
45pub struct TlsConfig {
46    config: Arc<ClientConfig>,
47}
48
49/// Accepts a certificate whose chain verifies against the configured CA but
50/// whose names do not match the address dialled. Every other failure
51/// (unknown CA, expired, bad signature, wrong key usage) still fails.
52#[derive(Debug)]
53struct AnyName(Arc<WebPkiServerVerifier>);
54
55impl ServerCertVerifier for AnyName {
56    fn verify_server_cert(
57        &self,
58        end_entity: &CertificateDer<'_>,
59        intermediates: &[CertificateDer<'_>],
60        server_name: &ServerName<'_>,
61        ocsp_response: &[u8],
62        now: UnixTime,
63    ) -> Result<ServerCertVerified, rustls::Error> {
64        // WebPkiServerVerifier checks the chain before the name, so a name
65        // error means the chain is good.
66        match self
67            .0
68            .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now)
69        {
70            Err(rustls::Error::InvalidCertificate(
71                CertificateError::NotValidForName | CertificateError::NotValidForNameContext { .. },
72            )) => Ok(ServerCertVerified::assertion()),
73            r => r,
74        }
75    }
76
77    fn verify_tls12_signature(
78        &self,
79        message: &[u8],
80        cert: &CertificateDer<'_>,
81        dss: &DigitallySignedStruct,
82    ) -> Result<HandshakeSignatureValid, rustls::Error> {
83        self.0.verify_tls12_signature(message, cert, dss)
84    }
85
86    fn verify_tls13_signature(
87        &self,
88        message: &[u8],
89        cert: &CertificateDer<'_>,
90        dss: &DigitallySignedStruct,
91    ) -> Result<HandshakeSignatureValid, rustls::Error> {
92        self.0.verify_tls13_signature(message, cert, dss)
93    }
94
95    fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
96        self.0.supported_verify_schemes()
97    }
98}
99
100impl TlsConfig {
101    /// From PEM bytes: the CA certificate(s) to trust, your client
102    /// certificate chain, and its private key (PKCS#8, PKCS#1 or SEC1).
103    /// The server certificate must name the host you connect to.
104    pub fn from_pem(ca: &[u8], client_cert: &[u8], client_key: &[u8]) -> io::Result<Self> {
105        Self::build(ca, client_cert, client_key, true)
106    }
107
108    /// [`from_pem`](Self::from_pem), reading the three PEM files.
109    pub fn from_pem_files(
110        ca: impl AsRef<Path>,
111        client_cert: impl AsRef<Path>,
112        client_key: impl AsRef<Path>,
113    ) -> io::Result<Self> {
114        Self::from_pem(
115            &std::fs::read(ca)?,
116            &std::fs::read(client_cert)?,
117            &std::fs::read(client_key)?,
118        )
119    }
120
121    /// Like [`from_pem`](Self::from_pem), but a server certificate that does
122    /// not name the host you dialled is accepted, as long as it chains to
123    /// `ca`. Use it when you reach the server by an IP address or an
124    /// internal name its certificate does not list: rustls (like browsers)
125    /// does not fall back to the certificate's common name, and a TAK
126    /// Server certificate made with only a CN fails the name check. An
127    /// untrusted, expired or self-signed-by-someone-else certificate still
128    /// fails.
129    pub fn from_pem_any_name(ca: &[u8], client_cert: &[u8], client_key: &[u8]) -> io::Result<Self> {
130        Self::build(ca, client_cert, client_key, false)
131    }
132
133    /// Your own rustls client configuration.
134    pub fn from_rustls(config: Arc<ClientConfig>) -> Self {
135        TlsConfig { config }
136    }
137
138    /// The rustls client configuration in use.
139    pub fn rustls_config(&self) -> &Arc<ClientConfig> {
140        &self.config
141    }
142
143    fn build(ca: &[u8], cert: &[u8], key: &[u8], check_name: bool) -> io::Result<Self> {
144        let mut roots = RootCertStore::empty();
145        for c in CertificateDer::pem_slice_iter(ca) {
146            roots
147                .add(c.map_err(|e| invalid(format!("CA PEM: {e}")))?)
148                .map_err(|e| invalid(format!("CA certificate: {e}")))?;
149        }
150        if roots.is_empty() {
151            return Err(invalid("CA PEM: no certificate found"));
152        }
153        let chain = CertificateDer::pem_slice_iter(cert)
154            .collect::<Result<Vec<_>, _>>()
155            .map_err(|e| invalid(format!("client certificate PEM: {e}")))?;
156        if chain.is_empty() {
157            return Err(invalid("client certificate PEM: no certificate found"));
158        }
159        let key = PrivateKeyDer::from_pem_slice(key)
160            .map_err(|e| invalid(format!("client key PEM: {e}")))?;
161        let provider = provider();
162        let builder = ClientConfig::builder_with_provider(provider.clone())
163            .with_safe_default_protocol_versions()
164            .map_err(invalid)?;
165        let roots = Arc::new(roots);
166        let builder = if check_name {
167            builder.with_root_certificates(roots)
168        } else {
169            let webpki = WebPkiServerVerifier::builder_with_provider(roots, provider)
170                .build()
171                .map_err(invalid)?;
172            builder
173                .dangerous()
174                .with_custom_certificate_verifier(Arc::new(AnyName(webpki)))
175        };
176        let config = builder
177            .with_client_auth_cert(chain, key)
178            .map_err(|e| invalid(format!("client certificate and key: {e}")))?;
179        Ok(TlsConfig {
180            config: Arc::new(config),
181        })
182    }
183}
184
185/// Sends events over one TLS connection to a TAK Server streaming input,
186/// for example `takserver:8089`. The handshake (including the client
187/// certificate) completes in `connect`, so a wrong CA or a rejected
188/// certificate fails there, not on the first event.
189///
190/// ```no_run
191/// use uas_cot::net::{TlsConfig, TlsSender};
192///
193/// let tls = TlsConfig::from_pem_files("ca.pem", "user.pem", "user.key")?;
194/// let mut tak = TlsSender::connect("takserver.example:8089", &tls)?;
195/// tak.send(&uas_cot::Event::new("test-1", "a-f-G", uas_cot::now_us(), 60))?;
196/// # Ok::<(), std::io::Error>(())
197/// ```
198#[derive(Debug)]
199pub struct TlsSender {
200    stream: StreamOwned<ClientConnection, TcpStream>,
201}
202
203/// The host part of `host:port`, `[v6]:port` or a bare host.
204fn host_of(addr: &str) -> &str {
205    if let Some(rest) = addr.strip_prefix('[') {
206        return rest.split(']').next().unwrap_or(rest);
207    }
208    match addr.rsplit_once(':') {
209        Some((h, p)) if !h.contains(':') && p.chars().all(|c| c.is_ascii_digit()) => h,
210        _ => addr,
211    }
212}
213
214impl TlsSender {
215    /// Connects to `addr` (`host:port`) and checks the server certificate
216    /// against `host`.
217    pub fn connect(addr: &str, config: &TlsConfig) -> io::Result<Self> {
218        Self::connect_named(addr, host_of(addr), config)
219    }
220
221    /// Connects to `addr` and checks the server certificate against
222    /// `server_name` (a DNS name or an IP address), for a server you reach
223    /// by one address and whose certificate names another.
224    pub fn connect_named(
225        addr: impl ToSocketAddrs,
226        server_name: &str,
227        config: &TlsConfig,
228    ) -> io::Result<Self> {
229        let name = ServerName::try_from(server_name.to_string())
230            .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e))?;
231        let mut sock = TcpStream::connect(addr)?;
232        sock.set_nodelay(true)?;
233        let mut conn = ClientConnection::new(config.config.clone(), name)
234            .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
235        while conn.is_handshaking() {
236            conn.complete_io(&mut sock)?;
237        }
238        Ok(TlsSender {
239            stream: StreamOwned::new(conn, sock),
240        })
241    }
242
243    /// Sends one event and flushes it to the socket.
244    pub fn send(&mut self, event: &Event) -> io::Result<()> {
245        super::write_event(&mut self.stream, event)?;
246        self.stream.flush()
247    }
248
249    /// The TLS stream, for reading what the server sends back (TAK Server
250    /// streams other clients' events to a connected client).
251    pub fn stream_mut(&mut self) -> &mut StreamOwned<ClientConnection, TcpStream> {
252        &mut self.stream
253    }
254
255    /// Sends a TLS close_notify and flushes it, so the server sees a clean
256    /// end of stream rather than a truncated one.
257    pub fn close(mut self) -> io::Result<()> {
258        self.stream.conn.send_close_notify();
259        self.stream.flush()
260    }
261}
262
263#[cfg(test)]
264mod tests {
265    use super::host_of;
266
267    #[test]
268    fn host_part() {
269        assert_eq!(host_of("takserver:8089"), "takserver");
270        assert_eq!(host_of("10.0.0.5:8089"), "10.0.0.5");
271        assert_eq!(host_of("[fd00::5]:8089"), "fd00::5");
272        assert_eq!(host_of("fd00::5"), "fd00::5");
273        assert_eq!(host_of("takserver"), "takserver");
274    }
275}