rustunnel 0.1.2

Sandboxed TLS tunnel library
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
//
// Copyright (C) 2019, 2020 Signal Messenger, LLC.
// All rights reserved.
//
// SPDX-License-Identifier: AGPL-3.0-or-later
//

//! TLS-related types.

use std::collections::HashSet;
use std::fs;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::os::unix::io::{AsRawFd, RawFd};
use std::path::Path;

use failure::ResultExt;
use log::warn;
use openssl::pkcs12;
use openssl::ssl;
use openssl::x509;

use super::stream::{ProxyRead, ProxyStreamError, ProxyWrite};

/// A TLS hostname specification.
///
/// This enum specifies the set of hostnames to trust when authenticating a TLS peer.
pub enum TlsHostname {
    /// Accept any hostname.
    AcceptInvalid,
    /// Accept one specific hostname.
    Hostname(String),
}

/// A TLS identity, comprised of a certificate and private key.
///
/// This struct provides both a certificate for a TLS peer to authenticate and its corresponding private key to use for
/// the TLS connection. Currently the only supported way of providing a certificate and private key is with a PKCS#12
/// container.
pub struct Identity {
    pkcs12: pkcs12::ParsedPkcs12,
}

/// A TLS CA certificate specification.
///
/// This enum specifies the set of CA certificates to trust when authenticating a TLS peer.
pub enum CaCertificate {
    /// Accept any CA certificates in the system's CA certificate store.
    System,
    /// Accept an openssl [`X509`](x509::X509) CA certificate.
    Custom {
        /// The openssl [`X509`](x509::X509) CA certificate to trust.
        x509: x509::X509,
    },
}

pub(crate) struct TlsAcceptor {
    acceptor: ssl::SslAcceptor,
}

pub(crate) struct TlsConnector {
    connector: ssl::SslConnector,
    hostname:  TlsHostname,
}

pub(crate) struct MidHandshakeTlsStream<T> {
    stream: ssl::MidHandshakeSslStream<T>,
}

pub(crate) struct TlsStream<T> {
    stream: ssl::SslStream<T>,
}

pub(crate) enum HandshakeError<T> {
    Failure(HandshakeFailure),
    WantRead(MidHandshakeTlsStream<T>),
    WantWrite(MidHandshakeTlsStream<T>),
}

#[derive(Debug, failure::Fail)]
pub(crate) enum HandshakeFailure {
    #[fail(display = "{} ({})", _0, _1)]
    VerifyError(ssl::Error, x509::X509VerifyResult),
    #[fail(display = "{}", _0)]
    SetupError(openssl::error::ErrorStack),
    #[fail(display = "{}", _0)]
    OtherError(ssl::Error),
}

#[cfg(target_os = "linux")]
pub(crate) fn configure_openssl_for_seccomp() -> Result<(), failure::Error> {
    openssl::rand::keep_random_devices_open(true);
    openssl::rand::rand_bytes(&mut [0; 1]).context("error setting up openssl rand")?;
    Ok(())
}

//
// TlsAcceptor impls
//

impl TlsAcceptor {
    pub fn new(tls_identity: Identity, tls_ca_cert: CaCertificate) -> Result<Self, failure::Error> {
        let mut acceptor = ssl::SslAcceptor::mozilla_intermediate_v5(ssl::SslMethod::tls()).context("error creating acceptor")?;

        // replace the cert_store with a new empty one, since `SslConnector::builder` might in the future call
        // `SSL_CTX_set_default_verify_paths` which would cause seccomp violations when openssl tries to load the system
        // trusted certs automatically as a fallback (and redundantly, since we already load them manually if we're
        // using them)
        let empty_cert_store = x509::store::X509StoreBuilder::new().context("error creating empty certificate store")?;
        acceptor.set_cert_store(empty_cert_store.build());

        acceptor
            .set_private_key(&tls_identity.pkcs12.pkey)
            .context("error setting server private key")?;
        acceptor
            .set_certificate(&tls_identity.pkcs12.cert)
            .context("error setting server certificate")?;
        if let Some(chain) = tls_identity.pkcs12.chain {
            for cert in chain.iter().rev() {
                acceptor
                    .add_extra_chain_cert(cert.to_owned())
                    .context("error adding server certificate chain")?;
            }
        }

        acceptor
            .set_min_proto_version(Some(ssl::SslVersion::TLS1_2))
            .context("error setting minimum tls version")?;
        acceptor
            .set_max_proto_version(Some(ssl::SslVersion::TLS1_2))
            .context("error setting maximum tls version")?;

        acceptor.set_session_cache_mode(ssl::SslSessionCacheMode::OFF);

        let mut verify_mode = ssl::SslVerifyMode::empty();
        verify_mode.insert(ssl::SslVerifyMode::PEER);
        verify_mode.insert(ssl::SslVerifyMode::FAIL_IF_NO_PEER_CERT);
        acceptor.set_verify(verify_mode);

        let mut cert_store = x509::store::X509StoreBuilder::new().context("error creating ca certificate store")?;
        match tls_ca_cert {
            CaCertificate::System => {
                return Err(failure::format_err!(
                    "cannot use system ca certificates for client certificate validation"
                ));
            }
            CaCertificate::Custom { x509: tls_ca_cert_x509 } => {
                cert_store
                    .add_cert(tls_ca_cert_x509)
                    .context("error adding custom ca certificate")?;
            }
        }
        acceptor
            .set_verify_cert_store(cert_store.build())
            .context("error setting ca certificate store")?;

        Ok(Self {
            acceptor: acceptor.build(),
        })
    }

    pub fn accept<T: Read + Write>(&self, stream: T) -> Result<TlsStream<T>, HandshakeError<T>> {
        self.acceptor.accept(stream).map(TlsStream::new).map_err(HandshakeError::from)
    }
}

//
// TlsConnector impls
//

impl TlsConnector {
    pub fn new(
        maybe_tls_identity: Option<Identity>,
        tls_hostname: TlsHostname,
        tls_ca_certs: Vec<CaCertificate>,
    ) -> Result<Self, failure::Error>
    {
        let mut connector =
            ssl::SslConnector::builder(ssl::SslMethod::tls()).context("error creating connector")?;

        // replace the cert_store with a new empty one, since `SslConnector::builder` calls
        // `SSL_CTX_set_default_verify_paths` which causes seccomp violations when openssl tries to load the system
        // trusted certs automatically as a fallback (and redundantly, since we already load them manually if we're
        // using them)
        let empty_cert_store = x509::store::X509StoreBuilder::new().context("error creating empty certificate store")?;
        connector.set_cert_store(empty_cert_store.build());

        if let Some(tls_identity) = maybe_tls_identity {
            connector
                .set_private_key(&tls_identity.pkcs12.pkey)
                .context("error setting client private key")?;
            connector
                .set_certificate(&tls_identity.pkcs12.cert)
                .context("error setting client certificate")?;
            if let Some(chain) = tls_identity.pkcs12.chain {
                for cert in chain.iter().rev() {
                    connector
                        .add_extra_chain_cert(cert.to_owned())
                        .context("error adding client certificate chain")?;
                }
            }
        }

        connector
            .set_min_proto_version(Some(ssl::SslVersion::TLS1_2))
            .context("error setting minimum tls version")?;
        connector
            .set_max_proto_version(Some(ssl::SslVersion::TLS1_2))
            .context("error setting maximum tls version")?;

        let mut cert_store = x509::store::X509StoreBuilder::new().context("error creating ca certificate store")?;
        for tls_ca_cert in tls_ca_certs {
            match tls_ca_cert {
                CaCertificate::System => {
                    add_system_ca_certificates(&mut cert_store).context("error adding system ca certificates")?;
                }
                CaCertificate::Custom { x509: tls_ca_cert_x509 } => {
                    cert_store
                        .add_cert(tls_ca_cert_x509)
                        .context("error adding custom ca certificate")?;
                }
            }
        }
        connector
            .set_verify_cert_store(cert_store.build())
            .context("error setting ca certificate store")?;

        Ok(TlsConnector {
            connector: connector.build(),
            hostname:  tls_hostname,
        })
    }

    pub fn connect<T: Read + Write>(&self, stream: T) -> Result<TlsStream<T>, HandshakeError<T>> {
        let mut connect_config = self
            .connector
            .configure()
            .map_err(|error| HandshakeError::Failure(HandshakeFailure::SetupError(error)))?;

        let hostname = match &self.hostname {
            TlsHostname::Hostname(hostname) => &hostname,
            TlsHostname::AcceptInvalid => {
                connect_config.set_verify_hostname(false);
                connect_config.set_use_server_name_indication(false);
                ""
            }
        };

        connect_config
            .connect(hostname, stream)
            .map(TlsStream::new)
            .map_err(HandshakeError::from)
    }
}

//
// Hostname impls
//

impl TlsHostname {
    /// Constructs a new [`TlsHostname`] from a [`String`].
    pub fn new(hostname: String) -> Self {
        Self::Hostname(hostname)
    }
}

//
// Identity impls
//

impl Identity {
    /// Constructs a new [`Identity`] from a PKCS#12 file at `path` encrypted with the given `password`.
    ///
    /// This function takes care to clear intermediate secrets in memory while parsing the file, as recommended by the
    /// [crate-level documentation](crate).
    ///
    /// # Errors
    ///
    /// If the PKCS#12 file is invalid or could not be read, or if the given `password` is incorrect, then an error is
    /// returned.
    pub fn from_pkcs12_file(path: &Path, password: &str) -> Result<Self, failure::Error> {
        let mut file = File::open(path)?;
        let file_len = file.metadata()?.len() as usize;
        let mut data = clear_on_drop::ClearOnDrop::new(vec![0; file_len].into_boxed_slice());

        file.read_exact(data.as_mut())?;

        Self::from_pkcs12(&data, password)
    }

    /// Constructs a new [`Identity`] from PKCS#12 `data` encrypted with the given `password`.
    ///
    /// # Errors
    ///
    /// If the PKCS#12 data is invalid or the given `password` is incorrect, then an error is returned.
    pub fn from_pkcs12(data: &[u8], password: &str) -> Result<Self, failure::Error> {
        let pkcs12 = pkcs12::Pkcs12::from_der(data)?.parse(password)?;
        Ok(Self { pkcs12 })
    }
}

//
// CaCertificate impls
//

impl CaCertificate {
    /// Constructs a [`CaCertificate::Custom`] from PEM `data`.
    ///
    /// # Errors
    ///
    /// If the PEM data is invalid, then an error is returned.
    pub fn from_pem(data: &[u8]) -> Result<Self, failure::Error> {
        match x509::X509::from_pem(data) {
            Ok(x509) => Ok(Self::Custom { x509 }),
            Err(error) => Err(failure::Error::from(error)),
        }
    }
}

//
// MidHandshakeTlsStream
//

impl<T: Read + Write> MidHandshakeTlsStream<T> {
    pub fn handshake(self) -> Result<TlsStream<T>, HandshakeError<T>> {
        self.stream.handshake().map(TlsStream::new).map_err(HandshakeError::from)
    }
}

impl<T: AsRawFd> AsRawFd for MidHandshakeTlsStream<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.stream.get_ref().as_raw_fd()
    }
}

//
// TlsStream impls
//

impl<T> TlsStream<T> {
    fn new(stream: ssl::SslStream<T>) -> Self {
        Self { stream }
    }
}

impl<T: Read + Write> ProxyRead for TlsStream<T> {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, ProxyStreamError> {
        match self.stream.ssl_read(buf) {
            Err(ref error) if error.code() == ssl::ErrorCode::ZERO_RETURN => Ok(0),
            result => openssl_to_proxy_stream_result(result),
        }
    }
}

impl<T: Read + Write> ProxyWrite for TlsStream<T> {
    fn write(&mut self, buf: &[u8]) -> Result<usize, ProxyStreamError> {
        openssl_to_proxy_stream_result(self.stream.ssl_write(buf))
    }

    fn shutdown(&mut self) -> Result<(), ProxyStreamError> {
        openssl_to_proxy_stream_result(self.stream.shutdown().map(drop))
    }
}

impl<T: AsRawFd> AsRawFd for TlsStream<T> {
    fn as_raw_fd(&self) -> RawFd {
        self.stream.get_ref().as_raw_fd()
    }
}

fn openssl_to_proxy_stream_result<T>(result: Result<T, ssl::Error>) -> Result<T, ProxyStreamError> {
    match result {
        Ok(value) => Ok(value),
        Err(ref error) if error.code() == ssl::ErrorCode::WANT_READ => Err(ProxyStreamError::WantRead),
        Err(ref error) if error.code() == ssl::ErrorCode::WANT_WRITE => Err(ProxyStreamError::WantWrite),
        Err(ref error) if error.code() == ssl::ErrorCode::SYSCALL && error.io_error().is_none() => {
            Err(ProxyStreamError::Io(io::Error::new(io::ErrorKind::UnexpectedEof, "tcp closed")))
        }
        Err(error) => {
            let error = error
                .into_io_error()
                .unwrap_or_else(|error| io::Error::new(io::ErrorKind::Other, error));
            Err(ProxyStreamError::Io(error))
        }
    }
}

//
// HandshakeError impls
//

impl<T> From<ssl::HandshakeError<T>> for HandshakeError<T> {
    fn from(error: ssl::HandshakeError<T>) -> Self {
        match error {
            ssl::HandshakeError::SetupFailure(error) => Self::Failure(HandshakeFailure::SetupError(error)),
            ssl::HandshakeError::Failure(stream) => Self::from(stream),
            ssl::HandshakeError::WouldBlock(stream) => match stream.error().code() {
                ssl::ErrorCode::WANT_READ => Self::WantRead(MidHandshakeTlsStream { stream }),
                ssl::ErrorCode::WANT_WRITE => Self::WantWrite(MidHandshakeTlsStream { stream }),
                _ => unreachable!(),
            },
        }
    }
}
impl<T> From<ssl::MidHandshakeSslStream<T>> for HandshakeError<T> {
    fn from(stream: ssl::MidHandshakeSslStream<T>) -> Self {
        let verify_result = stream.ssl().verify_result();
        let error = stream.into_error();
        if verify_result != x509::X509VerifyResult::OK {
            Self::Failure(HandshakeFailure::VerifyError(error, verify_result))
        } else {
            Self::Failure(HandshakeFailure::OtherError(error))
        }
    }
}

//
// internal
//

fn add_system_ca_certificates(store: &mut x509::store::X509StoreBuilder) -> Result<(), failure::Error> {
    let system_cert_dir = fs::read_dir(Path::new(r"/etc/ssl/certs/")).context("error reading /etc/ssl/certs/")?;
    let mut read_files = HashSet::new();
    for dir_entry_result in system_cert_dir {
        let dir_entry_path = dir_entry_result.context("error reading /etc/ssl/certs/")?.path();
        match dir_entry_path.canonicalize() {
            Ok(canonical_path) => {
                if !read_files.contains(&canonical_path) {
                    match add_certificate_file(store, &canonical_path) {
                        Ok(()) => (),
                        Err(error) => {
                            warn!("error reading system certificate {}: {}", canonical_path.display(), error);
                        }
                    }
                    read_files.insert(canonical_path);
                }
            }
            Err(error) => {
                warn!("error reading system certificate {}: {}", dir_entry_path.display(), error);
            }
        }
    }
    Ok(())
}

fn add_certificate_file(store: &mut x509::store::X509StoreBuilder, path: &Path) -> Result<(), failure::Error> {
    if path.is_dir() {
        return Ok(());
    }
    let data = fs::read(path).context("error reading file")?;
    let x509 = x509::X509::from_pem(&data).context("invaild pem data")?;
    store.add_cert(x509).context("error adding ca certificate to store")?;
    Ok(())
}