libtls 0.0.1

Basic Rust bindings to OpenBSD's libtls
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! This library crate provides mid-level bindings to the libtls API, provided
//! by OpenBSD's libressl.
//!
//! ## Example
//! 
//!     use std::io::prelude::*;
//!     use libtls::*;
//!     let init = Init::init();
//!     let mut config = Config::new(init);
//!     config.insecure_noverifycert();
//!     let mut stream = config
//!         .connect(("google.com", 443))
//!         .expect("connection failed");
//!     let mut buf = vec![0; 32];
//!     stream.write(&mut buf).expect("write failed");
//!     stream.close().expect("close failed");

// This file is distributed under the same terms as Rust itself.

#[macro_use] extern crate lazy_static;
extern crate libtls_sys;
#[macro_use] extern crate quick_error;
use libtls_sys::*;
use std::borrow::Cow;
use std::convert::AsRef;
use std::default::Default;
use std::ffi::{NulError, CString, CStr};
use std::io::{self, Read, Write};
use std::net::{self, ToSocketAddrs, TcpStream, SocketAddr};
use std::os::unix::io::{FromRawFd, IntoRawFd};
use std::os::unix::ffi::OsStrExt;
use std::ptr;
use std::path::Path;

/// The global TLS context. This object exists to represent the global state
/// in libtls. Retrieving another instance with `Init::init()` is not that
/// expensive, but copying it is free and it has zero size.
// According to the `tls_init` manpage, the function can safely be called more
// than once, but it cannot be called concurrently. Since we want to be fully
// thread safe, we need to make sure that can't happen.
#[derive(Copy, Clone)]
pub struct Init(());
lazy_static!{
    static ref TLS_INIT: Init = unsafe { Init::new() };
}
impl Init {
    /// Prepare the TLS state. This is not safe to call concurrently.
    unsafe fn new() -> Init {
        if tls_init() == -1 {
            panic!("TLS init failed.");
        }
        Init(())
    }
    /// Prepare the TLS state, if it has not already been called.
    pub fn init() -> Init {
        *TLS_INIT
    }
}

quick_error! {
    #[derive(Debug)]
    /// Errors that can result from running one of the `Config::Connect` functions.
    pub enum ConnectError {
        InvalidHostError {}
        IoError(err: io::Error) {
            from()
            cause(err)
        }
    }
}

/// This is a variant of `ToSocketAddrs` that provides a name to verify with.
pub trait ToNamedSocketAddrs: ToSocketAddrs {
    fn host(&self) -> Cow<str>;
}

impl<'a> ToNamedSocketAddrs for (&'a str, u16) {
    fn host(&self) -> Cow<str> {
        Cow::Borrowed(&self.0)
    }
}

impl<'a> ToNamedSocketAddrs for &'a str {
    fn host(&self) -> Cow<str> {
        // This logic should closely mirror the logic in libstd/net/addrs.rs
        // If it is a valid socket address in itself, then this is the name.
        if let Ok(addr) = self.parse::<SocketAddr>() {
            return Cow::Owned(addr.ip().to_string());
        }
        // If it has a port number, it's not part of the name.
        let mut parts_it = self.rsplitn(2, ':');
        if let (Some(_port), Some(host)) = (parts_it.next(), parts_it.next()) {
            Cow::Borrowed(host)
        } else {
            Cow::Borrowed(self)
        }
    }
}

/// A TLS connection builder.
pub struct Config(*mut Struct_tls_config);
impl Config {
    /// Construct a default configuration.
    pub fn new(_: Init) -> Config {
        let raw_config = unsafe { tls_config_new() };
        if raw_config.is_null() {
            panic!("TLS configuration failed to allocate.");
        }
        Config(raw_config)
    }
    /// Create a client connection to a TCP stream.
    pub fn connect<A: ToNamedSocketAddrs+Clone>(&self, addr: A)
            -> Result<Stream, ConnectError> {
        self.connect_name(addr.clone(), &*addr.host())
    }
    /// Create a client connection to a TCP stream, with a manually supplied
    /// host name.
    pub fn connect_name<A: ToSocketAddrs>(&self, addr: A, host: &str)
            -> Result<Stream, ConnectError> {
        self.connect_stream(try!(TcpStream::connect(addr)), host)
    }
    /// Connect a client connection to a raw stream, 
    pub fn connect_stream(&self, stream: TcpStream, host: &str)
            -> Result<Stream, ConnectError> {
        unsafe { Stream::do_connect(self, stream, host) }
    }
}
impl Default for Config {
    /// Construct a default configuration, and initialize TLS.
    fn default() -> Config {
        Config::new(Init::init())
    }
}
impl Drop for Config {
    fn drop(&mut self) {
        unsafe {
            tls_config_free(self.0)
        }
    }
}
impl Config {
    /// Set the directory where Certificate Authority files will be searched for.
    pub fn set_ca_path<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ()> {
        unsafe {
            tls_config_set_ca_path(self.0, path.as_ref().to_path_c_str().as_ptr())
                .as_tls_result_bare()
        }
    }
    /// Set the Certificate Authority file.
    pub fn set_ca_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ()> {
        unsafe {
            tls_config_set_ca_file(self.0, path.as_ref().to_path_c_str().as_ptr())
                .as_tls_result_bare()
        }
    }
    /// Set the Certificate Authority directly from memory.
    pub fn set_ca_mem(&mut self, cert: &[u8]) -> Result<(), ()> {
        unsafe {
            tls_config_set_ca_mem(self.0, &cert[0], cert.len())
                .as_tls_result_bare()
        }
    }
    /// Set the Certificate for thes machine from a file.
    pub fn set_cert_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ()> {
        unsafe {
            tls_config_set_cert_file(self.0, path.as_ref().to_path_c_str().as_ptr())
                .as_tls_result_bare()
        }
    }
    /// Set the Certificate directly from memory.
    pub fn set_cert_mem(&mut self, cert: &[u8]) -> Result<(), ()> {
        unsafe {
            tls_config_set_cert_mem(self.0, &cert[0], cert.len())
                .as_tls_result_bare()
        }
    }
    /// Set the enabled set of ciphers.
    pub fn set_ciphers(&mut self, ciphers: Ciphers) -> Result<(), ()> {
        unsafe {
            tls_config_set_ciphers(
                self.0,
                ciphers.0.as_ptr()
            ).as_tls_result_bare()
        }
    }
    /// Set the Private Key file.
    pub fn set_key_file<P: AsRef<Path>>(&mut self, path: P) -> Result<(), ()> {
        unsafe {
            tls_config_set_key_file(self.0, path.as_ref().to_path_c_str().as_ptr())
                .as_tls_result_bare()
        }
    }
    /// Set the Private Key directly from memory.
    pub fn set_key_mem(&mut self, cert: &[u8]) -> Result<(), ()> {
        unsafe {
            tls_config_set_key_mem(self.0, &cert[0], cert.len())
                .as_tls_result_bare()
        }
    }
    pub fn set_protocols(&mut self, protocols: Protocols) {
        unsafe {
            tls_config_set_protocols(self.0, protocols.0)
        }
    }
    /// Set the amount of steps back through the CA chain to go before
    /// considering a remote host untrusted.
    pub fn set_verify_depth(&mut self, verify_depth: u64) {
        unsafe {
            tls_config_set_verify_depth(self.0, verify_depth as libc::c_int);
        }
    }
    /// Prefer certificates set on the client. This is generally considered
    /// less secure.
    pub fn prefer_ciphers_client(&mut self) {
        unsafe {
            tls_config_prefer_ciphers_client(self.0);
        }
    }
    /// Prefer certificates on the server side. This is the default.
    pub fn prefer_ciphers_server(&mut self) {
        unsafe {
            tls_config_prefer_ciphers_server(self.0);
        }
    }
    /// Clear any secret keys from memory.
    pub fn clear_keys(&mut self) {
        unsafe {
            tls_config_clear_keys(self.0);
        }
    }
    /// Do not verify certificates. *Do not use this in production software*.
    pub fn insecure_noverifycert(&mut self) {
        unsafe {
            tls_config_insecure_noverifycert(self.0);
        }
    }
    /// Do not verify hostnames. *Do not use this in production software*.
    pub fn insecure_noverifyname(&mut self) {
        unsafe {
            tls_config_insecure_noverifyname(self.0);
        }
    }
    /// Do not verify that our clocks match up. *Do not use this in production
    /// software*.
    pub fn insecure_noverifytime(&mut self) {
        unsafe {
            tls_config_insecure_noverifytime(self.0);
        }
    }
    /// Re-enable verification.
    pub fn verify(&mut self) {
        unsafe {
            tls_config_verify(self.0);
        }
    }
    /// Enable client verification, and require the client to do so.
    pub fn verify_client(&mut self) {
        unsafe {
            tls_config_verify_client(self.0);
        }
    }
    /// Enable client verification, but do not require the client to send a
    /// certificate.
    pub fn verify_client_optional(&mut self) {
        unsafe {
            tls_config_verify_client_optional(self.0);
        }
    }
}

/// A list of enabled TLS protocols. Pass this to `Config::set_protocols`
#[derive(Debug, Clone)]
pub struct Protocols(libc::uint32_t);
impl Protocols {
    /// Construct a protocols list from a textual list, like a config file would use.
    pub fn from_str(protocols: &str) -> Result<Protocols, ()> {
        Init::init();
        let mut ret_val = Protocols(0);
        let protocols = try!(CString::new(protocols).map_err(|_| ()));
        unsafe {
            try!(
                tls_config_parse_protocols(&mut ret_val.0, protocols.as_ptr())
                    .as_tls_result_bare()
            )
        }
        Ok(ret_val)
    }
    /// Construct a secure default list of protocols.
    pub fn secure() -> Protocols {
        Protocols(libtls_sys::TLS_PROTOCOLS_DEFAULT)
    }
    /// Construct a backwards-compatible default list of protocols.
    pub fn all() -> Protocols {
        Protocols(libtls_sys::TLS_PROTOCOLS_ALL)
    }
    /// Construct a backwards-compatible default list of protocols.
    pub fn legacy() -> Protocols {
        Protocols::all()
    }
}
impl Default for Protocols {
    fn default() -> Protocols {
        Protocols::secure()
    }
}

/// A list of enabled encryption algorithms.
#[derive(Debug, Clone)]
pub struct Ciphers(CString);
impl Ciphers {
    /// Construct a cipher list from a textual list, like a config file would use.
    pub fn from_str(ciphers: &str) -> Result<Ciphers, NulError> {
        Ok(Ciphers(try!(CString::new(ciphers))))
    }
    /// Construct a secure default list of ciphers.
    pub fn secure() -> Ciphers {
        Ciphers::from_str("secure").expect("'secure' does not contain a nul")
    }
    /// Construct a backwards-compatible default list of ciphers.
    pub fn compat() -> Ciphers {
        Ciphers::from_str("compat").expect("'compat' does not contain a nul")
    }
    /// Construct a backwards-compatible default list of ciphers.
    pub fn legacy() -> Ciphers {
        Ciphers::compat()
    }
}
impl Default for Ciphers {
    fn default() -> Ciphers {
        Ciphers::secure()
    }
}

/// A TLS connection.
pub struct Stream {
    context: *mut Struct_tls,
    stream: TcpStream,
}
impl Stream {
    /// Create a client connection; the raw stream version.
    unsafe fn do_connect(config: &Config, stream: TcpStream, host: &str)
            -> Result<Self, ConnectError> {
        let host = try!(
            CString::new(host).map_err(|_| ConnectError::InvalidHostError)
        );
        let context = tls_client();
        if context.is_null() {
            panic!("TLS client building failed to allocate.");
        }
        let fd = stream.into_raw_fd();
        let mut result = Stream {
            stream: TcpStream::from_raw_fd(fd),
            context: context,
        };
        try!(tls_configure(context, config.0).as_tls_result_io(context));
        try!(result.run_to_completion(|| {
            tls_connect_socket(context, fd, host.as_ptr())
        }));
        Ok(result)
    }
    /// Connect with a default configuration.
    pub fn connect<A: ToNamedSocketAddrs+Clone>(addr: A)
            -> Result<Stream, ConnectError> {
        Config::default().connect(addr)
    }
    // Disconnect, complete with error handling!
    pub fn close(mut self) -> Result<(), io::Error> {
        unsafe { self.do_close() }
    }
    /// Get access to the underlying TCP stream.
    pub fn get_ref(&self) -> &TcpStream {
        &self.stream
    }
    /// Get access to the underlying TCP stream.
    pub fn get_mut(&mut self) -> &mut TcpStream {
        &mut self.stream
    }
    unsafe fn do_close(&mut self) -> Result<(), io::Error> {
        let context = self.context;
        try!(self.run_to_completion(|| {
            tls_close(context)
        }));
        tls_free(self.context);
        self.context = ptr::null_mut();
        try!(self.stream.shutdown(net::Shutdown::Both));
        Ok(())
    }
    unsafe fn run_to_completion<C, T>(&mut self, mut c: C)
            -> Result<T, io::Error>
            where C: FnMut() -> T, T: Into<libc::c_int> + Clone {
        loop {
            let result = c();
            match result.clone().into() {
                TLS_WANT_POLLIN | TLS_WANT_POLLOUT => (),
                -1 => {
                    return Err(io::Error::new(
                        io::ErrorKind::Other,
                        CStr::from_ptr(tls_error(self.context))
                            .to_string_lossy()
                            .into_owned()
                    ))
                }
                _ => return Ok(result),
            }
        }
    }
}
impl Read for Stream {
    fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
        let len = buf.len();
        let buf = &mut buf[0] as *mut u8 as *mut libc::c_void;
        unsafe {
            tls_read(self.context, buf, len)
                .as_tls_result_io_number(self.context).map(|x| x as usize)
        }
    }
}
impl Write for Stream {
    fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
        let len = buf.len();
        let buf = &buf[0] as *const u8 as *const libc::c_void;
        unsafe {
            tls_write(self.context, buf, len)
                .as_tls_result_io_number(self.context).map(|x| x as usize)
        }
    }
    fn flush(&mut self) -> Result<(), io::Error> {
        self.stream.flush()
    }
}
impl Drop for Stream {
    fn drop(&mut self) {
        if !self.context.is_null() {
            unsafe {
                self.do_close()
                    .expect("TLS connection close unexpectedly failed!");
            }
        }
    }
}

/// A utility function to get a path that's usable with libtls's API.
trait PathRawStr {
    fn to_path_c_str(&self) -> Cow<CStr>;
}
impl PathRawStr for Path {
    fn to_path_c_str(&self) -> Cow<CStr> {
        unsafe {
            Cow::Borrowed(
                CStr::from_ptr(
                    &self.as_os_str().as_bytes()[0] as *const u8 as *const libc::c_char
                )
            )
        }
    }
}

/// A utility function to convert negative-number-errors to `Result`s
trait AsTlsResult: Sized {
    fn as_tls_result_bare(&self) -> Result<(), ()>;
    fn as_tls_result_bare_number(&self) -> Result<Self, ()>;
    unsafe fn as_tls_result_io(&self, context: *mut Struct_tls)
        -> Result<(), io::Error>;
    unsafe fn as_tls_result_io_number(&self, context: *mut Struct_tls)
        -> Result<Self, io::Error>;
}
macro_rules! define_tls_result {
    ($t:ty) => (
        impl AsTlsResult for $t {
            fn as_tls_result_bare(&self) -> Result<(), ()> {
                if *self < 0 {
                    Err(())
                } else {
                    Ok(())
                }
            }
            fn as_tls_result_bare_number(&self) -> Result<$t, ()> {
                self.as_tls_result_bare().map(|_| *self)
            }
            unsafe fn as_tls_result_io(&self, context: *mut Struct_tls)
                    -> Result<(), io::Error> {
                if *self < 0 {
                    Err(io::Error::new(
                        io::ErrorKind::Other,
                        CStr::from_ptr(tls_error(context))
                            .to_string_lossy()
                            .into_owned()
                    ))
                } else {
                    Ok(())
                }
            }
            unsafe fn as_tls_result_io_number(&self, context: *mut Struct_tls)
                    -> Result<$t, io::Error> {
                self.as_tls_result_io(context).map(|_| *self)
            }
        }
    )
}
define_tls_result!(libc::c_int);
define_tls_result!(libc::ssize_t);

#[cfg(test)]
mod test;