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
#![deny(
    missing_docs,
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unsafe_code,
    unstable_features,
    unused_import_braces,
    unused_qualifications,
    dead_code
)]

//! This is a simple wrapper around the PSK functionality exposed by the [openssl crate](https://github.com/sfackler/rust-openssl). PR's to make this more generic, useable and informative (in terms of errors) are more than welcome.
//!
//! ## Features
//!
//! PSK Client has one feature which is `openssl-vendored` which simply enables the vendored feature on the openssl crate, for further information, see the [openssl-rs docs](https://docs.rs/openssl/0.10.19/openssl/#vendored).
//!
//! ## Usage
//!
//! ```rust
//! use psk_client::{PskClient, error::PskClientError};
//! use std::io::Write;
//!
//! fn main() -> Result<(), PskClientError> {
//!     let client = PskClient::builder("127.0.0.1:4433")
//!         .reset_ciphers()
//!         .cipher("PSK-AES128-CBC-SHA")
//!         .cipher("PSK-AES256-CBC-SHA")
//!         .identity("Client_identity")
//!         .key("4836525835726d466c743469426c55356e377375436254566d51476937724932")
//!         .build()?;
//!
//!     match client.connect() {
//!         Ok(mut connection) => {
//!             if let Err(msg) = connection.write_all(b"Hello, World!") {
//!                 eprintln!("Error writing to client: {}", msg);
//!             }
//!         }
//!         Err(e) => eprintln!("{}", e)
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! ## Default Ciphers
//!
//! By default the client will use the following cipher string, this can be cleared by calling `reset_ciphers()` on a `PskClientBuilder`. You can supply your own ciphers, either after clearing the pre-defined cipers, or in addition to
//! them by calling `cipher("<cipher>")` on a `PskClientBuilder`
//!
//! * `RSA-PSK-AES256-GCM-SHA384`
//! * `DHE-PSK-AES256-GCM-SHA384`
//! * `RSA-PSK-CHACHA20-POLY1305`
//! * `DHE-PSK-CHACHA20-POLY1305`
//! * `DHE-PSK-AES256-CCM8`
//! * `DHE-PSK-AES256-CCM`
//! * `PSK-AES256-GCM-SHA384`
//! * `PSK-CHACHA20-POLY1305`
//! * `PSK-AES256-CCM8`
//! * `PSK-AES256-CCM`
//! * `RSA-PSK-AES128-GCM-SHA256`
//! * `DHE-PSK-AES128-GCM-SHA256`
//!

/// module for client builder.
pub mod builder;
/// module for error handling.
pub mod error;

use crate::{
    builder::PskClientBuilder,
    error::{PskClientError, PskClientOpenSSLError},
};

use openssl::{
    error::ErrorStack,
    ssl::{SslConnector, SslConnectorBuilder, SslMethod, SslStream},
};

use openssl_errors::put_error;
use std::{io::Read, io::Write, net::SocketAddr, net::TcpStream, net::ToSocketAddrs};

/// The PSK client, this contains all the required information to generate
/// and return a connection to a TCP socket over SSL where PSK negotiation has
/// taken place.
#[derive(Clone, Debug, PartialEq)]
pub struct PskClient {
    host: SocketAddr,
    ciphers: String,
    identity: String,
    key: Vec<u8>,
}

/// Trait to abstract over Read and Write, this enables one to abstract over a TcpStream or an SslStream
/// like so:
///
/// ```rust,ignore
/// let socket = match should_use_psk {
///     true => get_psk_connector(),
///     false => get_plain_connector()
/// };
///
/// socket.write(b"ping").unwrap();
///
/// let mut buffer = Vec::new();
/// socket.read_to_end(&mut buffer);
///
/// ...
///
/// fn get_psk_connector() -> Box<dyn ReadWriteSocket> {
///     Box::new(PskClient::builder()...build().unwrap().connect().unwrap())
/// }
///
/// fn get_plain_connector() Box<dyn ReadWriteSocket> {
///     Box::new(TcpStream::connect("..").unwrap())
/// }
///
/// ```
pub trait ReadWriteSocket: Read + Write {}

impl ReadWriteSocket for TcpStream {}
impl ReadWriteSocket for SslStream<TcpStream> {}

impl PskClient {
    /// Returns a new instance of a `PskBuilder` for the given host.
    ///  ```rust
    /// use psk_client::PskClient;
    /// let builder = PskClient::builder("127.0.0.1:4433");
    /// ```
    pub fn builder<'a, H: ToSocketAddrs>(host: H) -> PskClientBuilder<'a, H> {
        PskClientBuilder::new(host)
    }

    /// Returns an SSL stream which wraps a TCP stream, does not consume the
    /// instance of `PskClient` thus that it may be called multiple times.
    /// ```rust
    /// use psk_client::PskClient;
    /// use std::io::Write;
    ///
    /// if let Ok(client) = PskClient::builder("127.0.0.1:4433")
    ///     .identity("some-client")
    ///     .key("1A2B3C4D")
    ///     .build()
    /// {
    ///     if let Ok(mut connection) = client.connect() {
    ///         connection.write_all(b"Hello, World!").unwrap();
    ///     }
    /// }
    /// ```
    pub fn connect(&self) -> Result<SslStream<TcpStream>, PskClientError> {
        let connector = self.build_client()?;

        let stream = TcpStream::connect(self.host).map_err(PskClientError::TcpConnectError)?;

        connector
            .connect(&self.host.to_string(), stream)
            .map_err(|e| PskClientError::SslHandshakeError(e.to_string()))
    }

    /// Returns a new `SslConnector`
    fn build_client(&self) -> Result<SslConnector, PskClientError> {
        let mut builder = self.ssl_builder()?;

        builder
            .set_cipher_list(&self.ciphers)
            .map_err(|e| PskClientError::InvalidCipherList(self.ciphers.to_owned(), e))?;

        let identity = self.identity.to_owned();
        let key = self.key.clone();

        builder.set_psk_client_callback(move |_ssl, _hint, mut identity_buffer, mut psk_buffer| {
            if let Err(err) = identity_buffer.write_all(identity.as_bytes()) {
                put_error!(
                    PskClientOpenSSLError::CONNECT_WRITE_ID,
                    PskClientOpenSSLError::IO_ERROR,
                    "{}",
                    err
                );
                return Err(ErrorStack::get());
            }

            if let Err(err) = psk_buffer.write_all(&key) {
                put_error!(
                    PskClientOpenSSLError::CONNECT_WRITE_KEY,
                    PskClientOpenSSLError::IO_ERROR,
                    "{}",
                    err
                );
                return Err(ErrorStack::get());
            }

            Ok(key.len())
        });

        Ok(builder.build())
    }

    /// Returns an `SslBuilder`
    fn ssl_builder(&self) -> Result<SslConnectorBuilder, PskClientError> {
        SslConnector::builder(SslMethod::tls()).map_err(PskClientError::FailedInitialisation)
    }
}