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
extern crate rustls;
extern crate hyper;
#[cfg(feature = "client")]
extern crate webpki_roots;

use std::io;
use std::sync::Arc;
use std::sync::{Mutex, MutexGuard};
use std::net::{SocketAddr, Shutdown};
use std::time::Duration;

use rustls::Session;
#[cfg(feature = "client")] pub use rustls::ClientSession;
#[cfg(feature = "server")] pub use rustls::ServerSession;

use hyper::net::{HttpStream, NetworkStream};
#[cfg(feature = "client")] use hyper::net::SslClient;
#[cfg(feature = "server")] use hyper::net::SslServer;

pub struct TlsStream<S: Session> {
    session: S,
    underlying: HttpStream,
}

impl<S: Session> TlsStream<S> {
    #[inline(always)]
    fn close(&mut self, how: Shutdown) -> io::Result<()> {
        self.underlying.close(how)
    }

    #[inline(always)]
    fn peer_addr(&mut self) -> io::Result<SocketAddr> {
        self.underlying.peer_addr()
    }

    #[inline(always)]
    fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.underlying.set_read_timeout(dur)
    }

    #[inline(always)]
    fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.underlying.set_write_timeout(dur)
    }
}

impl<S: Session> io::Read for TlsStream<S> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        loop {
            match self.session.read(buf)? {
                // If there's no plaintext, either we need to keep reading or
                // writing TLS-specific things or there's really nothing left.
                0 => {
                    if self.session.wants_write() {
                        self.session.write_tls(&mut self.underlying)?;
                    } else if self.session.wants_read() {
                        if self.session.read_tls(&mut self.underlying)? == 0 {
                            return Ok(0); // there is no data left to read.
                        } else {
                            if let Err(err) = self.session.process_new_packets() {
                                // flush queued messages before returning an Err
                                // in order to send alerts instead of abruptly
                                // closing the socket
                                if self.session.wants_write() {
                                    // ignore result to avoid masking original error
                                    let _ = self.session.write_tls(&mut self.underlying);
                                }

                                return Err(io::Error::new(io::ErrorKind::Other, err));
                            }
                        }
                    } else {
                        return Ok(0);
                    }
                }
                n => return Ok(n),
            }
        }
    }
}

impl<S: Session> io::Write for TlsStream<S> {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let len = self.session.write(buf)?;
        self.session.write_tls(&mut self.underlying)?;
        Ok(len)
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        let rc = self.session.flush();
        self.session.write_tls(&mut self.underlying)?;
        rc
    }
}

pub struct WrappedStream<S: Session>(Arc<Mutex<TlsStream<S>>>);

impl<S: Session> Clone for WrappedStream<S> {
    #[inline]
    fn clone(&self) -> Self {
        WrappedStream(self.0.clone())
    }
}

impl<S: Session> WrappedStream<S> {
    #[inline]
    fn lock(&self) -> MutexGuard<TlsStream<S>> {
        self.0.lock().unwrap_or_else(|e| e.into_inner())
    }
}

impl<S: Session> io::Read for WrappedStream<S> {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.lock().read(buf)
    }
}

impl<S: Session> io::Write for WrappedStream<S> {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.lock().write(buf)
    }

    #[inline]
    fn flush(&mut self) -> io::Result<()> {
        self.lock().flush()
    }
}

impl<S: Session + 'static> NetworkStream for WrappedStream<S> {
    #[inline]
    fn peer_addr(&mut self) -> io::Result<SocketAddr> {
        self.lock().peer_addr()
    }

    #[inline]
    fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.lock().set_read_timeout(dur)
    }

    #[inline]
    fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
        self.lock().set_write_timeout(dur)
    }

    #[inline]
    fn close(&mut self, how: Shutdown) -> io::Result<()> {
        self.lock().close(how)
    }
}

#[cfg(feature = "client")]
#[derive(Clone)]
pub struct TlsClient {
    pub cfg: Arc<rustls::ClientConfig>,
}

#[cfg(feature = "client")]
impl TlsClient {
    pub fn new() -> TlsClient {
        let mut tls_config = rustls::ClientConfig::new();
        let cache = rustls::ClientSessionMemoryCache::new(64);
        tls_config.set_persistence(cache);
        tls_config.root_store
            .add_server_trust_anchors(&webpki_roots::TLS_SERVER_ROOTS);

        TlsClient {
            cfg: Arc::new(tls_config),
        }
    }
}

#[cfg(feature = "client")]
impl SslClient for TlsClient {
    type Stream = WrappedStream<ClientSession>;

    #[inline]
    fn wrap_client(
        &self,
        stream: HttpStream,
        host: &str,
    ) -> hyper::Result<WrappedStream<ClientSession>> {
        let tls = TlsStream {
            session: rustls::ClientSession::new(&self.cfg, host),
            underlying: stream,
        };

        Ok(WrappedStream(Arc::new(Mutex::new(tls))))
    }
}

#[cfg(feature = "server")]
#[derive(Clone)]
pub struct TlsServer {
    pub cfg: Arc<rustls::ServerConfig>,
}

#[cfg(feature = "server")]
impl TlsServer {
    pub fn new(certs: Vec<rustls::Certificate>, key: rustls::PrivateKey) -> TlsServer {
        let mut tls_config = rustls::ServerConfig::new();
        let cache = rustls::ServerSessionMemoryCache::new(1024);
        tls_config.set_persistence(cache);
        tls_config.ticketer = rustls::Ticketer::new();
        tls_config.set_single_cert(certs, key);

        TlsServer {
            cfg: Arc::new(tls_config),
        }
    }

    #[inline]
    pub fn with_config(config: rustls::ServerConfig) -> TlsServer {
        TlsServer {
            cfg: Arc::new(config),
        }
    }
}

#[cfg(feature = "server")]
impl SslServer for TlsServer {
    type Stream = WrappedStream<ServerSession>;

    #[inline]
    fn wrap_server(&self, stream: HttpStream) -> hyper::Result<WrappedStream<ServerSession>> {
        let tls = TlsStream {
            session: rustls::ServerSession::new(&self.cfg),
            underlying: stream,
        };

        Ok(WrappedStream(Arc::new(Mutex::new(tls))))
    }
}

pub mod util {
    use std::fs;
    use std::io::{self, BufReader};
    use std::error;
    use std::fmt;

    use rustls;
    use rustls::internal::pemfile;
    use rustls::sign::RSASigningKey;

    #[derive(Debug)]
    pub enum Error {
        Io(io::Error),
        BadCerts,
        BadKeyCount,
        BadKey,
    }

    pub type Result<T> = ::std::result::Result<T, Error>;

    impl error::Error for Error {
        fn description(&self) -> &str {
            match *self {
                Error::Io(ref e) => e.description(),
                Error::BadCerts => "the contents of the certificates file were invalid",
                Error::BadKeyCount => "the private key file contained more than one key",
                Error::BadKey => "the contents of the private key file were invalid",
            }
        }
    }

    impl fmt::Display for Error {
        fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
            match *self {
                Error::Io(ref e) => write!(f, "I/O Error: {}", e),
                Error::BadCerts => write!(f, "invalid certificates file contents"),
                Error::BadKeyCount => write!(f, "more than one key in private key file"),
                Error::BadKey => write!(f, "invalid private key file contents"),
            }
        }
    }

    pub fn load_certs(filename: &str) -> Result<Vec<rustls::Certificate>> {
        let certfile = fs::File::open(filename).map_err(|e| Error::Io(e))?;
        let mut reader = BufReader::new(certfile);
        pemfile::certs(&mut reader).map_err(|_| Error::BadCerts)
    }

    pub fn load_private_key(filename: &str) -> Result<rustls::PrivateKey> {
        use std::io::Seek;
        use std::io::BufRead;

        let keyfile = fs::File::open(filename).map_err(Error::Io)?;
        let mut reader = BufReader::new(keyfile);

        // "rsa" (PKCS1) PEM files have a different first-line header than PKCS8
        // PEM files, use that to determine the parse function to use.
        let mut first_line = String::new();
        reader.read_line(&mut first_line).map_err(Error::Io)?;
        reader.seek(io::SeekFrom::Start(0)).map_err(Error::Io)?;

        let private_keys_fn = match first_line.trim_right() {
            "-----BEGIN RSA PRIVATE KEY-----" => pemfile::rsa_private_keys,
            "-----BEGIN PRIVATE KEY-----" => pemfile::pkcs8_private_keys,
            _ => return Err(Error::BadKey),
        };

        let key = private_keys_fn(&mut reader)
            .map_err(|_| Error::BadKey)
            .and_then(|mut keys| match keys.len() {
                0 => Err(Error::BadKey),
                1 => Ok(keys.remove(0)),
                _ => Err(Error::BadKeyCount),
            })?;

        // Ensure we can use the key.
        if RSASigningKey::new(&key).is_err() {
            Err(Error::BadKey)
        } else {
            Ok(key)
        }
    }
}