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
//! Run a secret-handshake and return a box-stream encrypted connection.
//!
//! This library uses libsodium internally. In application code, call
//! [`sodiumoxide::init()`](https://dnaq.github.io/sodiumoxide/sodiumoxide/fn.init.html)
//! before using any functions from this module.

#![deny(missing_docs)]

extern crate secret_handshake;
extern crate box_stream;
#[macro_use]
extern crate futures;
extern crate tokio_io;
extern crate sodiumoxide;

use std::io;

use futures::{Future, Async, Poll};
use tokio_io::{AsyncRead, AsyncWrite};
use sodiumoxide::crypto::{sign, box_};
use secret_handshake::*;
use box_stream::*;

/// A future that initiates a secret-handshake and then yields a channel that
/// encrypts/decrypts all data via box-stream.
pub struct Client<'a, S>(ClientHandshaker<'a, S>);

impl<'a, S: AsyncRead + AsyncWrite> Client<'a, S> {
    /// Create a new `Client` to connect to a server with known public key
    /// and app key over the given `stream`.
    ///
    /// Ephemeral keypairs can be generated via
    /// `sodiumoxide::crypto::box_::gen_keypair`.
    pub fn new(stream: S,
               network_identifier: &'a [u8; NETWORK_IDENTIFIER_BYTES],
               client_longterm_pk: &'a sign::PublicKey,
               client_longterm_sk: &'a sign::SecretKey,
               client_ephemeral_pk: &'a box_::PublicKey,
               client_ephemeral_sk: &'a box_::SecretKey,
               server_longterm_pk: &'a sign::PublicKey)
               -> Client<'a, S> {
        Client(ClientHandshaker::new(stream,
                                     network_identifier,
                                     client_longterm_pk,
                                     client_longterm_sk,
                                     client_ephemeral_pk,
                                     client_ephemeral_sk,
                                     server_longterm_pk))
    }
}

impl<'a, S: AsyncRead + AsyncWrite> Future for Client<'a, S> {
    type Item = Result<BoxDuplex<S>, (ClientHandshakeFailure, S)>;
    type Error = (io::Error, S);

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let (res, stream) = try_ready!(self.0.poll());
        match res {
            Ok(outcome) => {
                Ok(Async::Ready(Ok(BoxDuplex::new(stream,
                                                  outcome.encryption_key(),
                                                  outcome.decryption_key(),
                                                  outcome.encryption_nonce(),
                                                  outcome.decryption_nonce()))))
            }
            Err(failure) => Ok(Async::Ready(Err((failure, stream)))),
        }
    }
}

/// A future that initiates a secret-handshake and then yields a channel that
/// encrypts/decrypts all data via box-stream.
///
/// This copies the handshake keys so that it is not constrained by the key's lifetime.
pub struct OwningClient<S>(OwningClientHandshaker<S>);

impl<S: AsyncRead + AsyncWrite> OwningClient<S> {
    /// Create a new `OwningClient` to connect to a server with known public key
    /// and app key over the given `stream`.
    ///
    /// This copies the handshake keys so that it is not constrained by the key's lifetime.
    ///
    /// Ephemeral keypairs can be generated via
    /// `sodiumoxide::crypto::box_::gen_keypair`.
    pub fn new(stream: S,
               network_identifier: &[u8; NETWORK_IDENTIFIER_BYTES],
               client_longterm_pk: &sign::PublicKey,
               client_longterm_sk: &sign::SecretKey,
               client_ephemeral_pk: &box_::PublicKey,
               client_ephemeral_sk: &box_::SecretKey,
               server_longterm_pk: &sign::PublicKey)
               -> OwningClient<S> {
        OwningClient(OwningClientHandshaker::new(stream,
                                                 network_identifier,
                                                 client_longterm_pk,
                                                 client_longterm_sk,
                                                 client_ephemeral_pk,
                                                 client_ephemeral_sk,
                                                 server_longterm_pk))
    }
}

impl<S: AsyncRead + AsyncWrite> Future for OwningClient<S> {
    type Item = Result<BoxDuplex<S>, (ClientHandshakeFailure, S)>;
    type Error = (io::Error, S);

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let (res, stream) = try_ready!(self.0.poll());
        match res {
            Ok(outcome) => {
                Ok(Async::Ready(Ok(BoxDuplex::new(stream,
                                                  outcome.encryption_key(),
                                                  outcome.decryption_key(),
                                                  outcome.encryption_nonce(),
                                                  outcome.decryption_nonce()))))
            }
            Err(failure) => Ok(Async::Ready(Err((failure, stream)))),
        }
    }
}

/// A future that accepts a secret-handshake and then yields a channel that
/// encrypts/decrypts all data via box-stream.
pub struct Server<'a, S>(ServerHandshaker<'a, S>);

impl<'a, S: AsyncRead + AsyncWrite> Server<'a, S> {
    /// Create a new `Server` to accept a connection from a client which knows
    /// the server's public key and uses the right app key over the given
    /// `stream`.
    ///
    /// Ephemeral keypairs can be generated via
    /// `sodiumoxide::crypto::box_::gen_keypair`.
    pub fn new(stream: S,
               network_identifier: &'a [u8; NETWORK_IDENTIFIER_BYTES],
               server_longterm_pk: &'a sign::PublicKey,
               server_longterm_sk: &'a sign::SecretKey,
               server_ephemeral_pk: &'a box_::PublicKey,
               server_ephemeral_sk: &'a box_::SecretKey)
               -> Server<'a, S> {
        Server(ServerHandshaker::new(stream,
                                     network_identifier,
                                     server_longterm_pk,
                                     server_longterm_sk,
                                     &server_ephemeral_pk,
                                     &server_ephemeral_sk))
    }
}

impl<'a, S: AsyncRead + AsyncWrite> Future for Server<'a, S> {
    /// On success, the result contains the encrypted connection and the
    /// longterm public key of the client.
    type Item = Result<(BoxDuplex<S>, sign::PublicKey), (ServerHandshakeFailure, S)>;
    type Error = (io::Error, S);

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let (res, stream) = try_ready!(self.0.poll());
        match res {
            Ok(outcome) => {
                Ok(Async::Ready(Ok((BoxDuplex::new(stream,
                                                   outcome.encryption_key(),
                                                   outcome.decryption_key(),
                                                   outcome.encryption_nonce(),
                                                   outcome.decryption_nonce()),
                                    outcome.peer_longterm_pk()))))
            }
            Err(failure) => Ok(Async::Ready(Err((failure, stream)))),
        }
    }
}

/// A future that accepts a secret-handshake and then yields a channel that
/// encrypts/decrypts all data via box-stream.
///
/// This copies the handshake keys so that it is not constrained by the key's lifetime.
pub struct OwningServer<S>(OwningServerHandshaker<S>);

impl<S: AsyncRead + AsyncWrite> OwningServer<S> {
    /// Create a new `Server` to accept a connection from a client which knows
    /// the server's public key and uses the right app key over the given
    /// `stream`.
    ///
    /// This copies the handshake keys so that it is not constrained by the key's lifetime.
    ///
    /// Ephemeral keypairs can be generated via
    /// `sodiumoxide::crypto::box_::gen_keypair`.
    pub fn new(stream: S,
               network_identifier: &[u8; NETWORK_IDENTIFIER_BYTES],
               server_longterm_pk: &sign::PublicKey,
               server_longterm_sk: &sign::SecretKey,
               server_ephemeral_pk: &box_::PublicKey,
               server_ephemeral_sk: &box_::SecretKey)
               -> OwningServer<S> {
        OwningServer(OwningServerHandshaker::new(stream,
                                                 network_identifier,
                                                 server_longterm_pk,
                                                 server_longterm_sk,
                                                 &server_ephemeral_pk,
                                                 &server_ephemeral_sk))
    }
}

impl<S: AsyncRead + AsyncWrite> Future for OwningServer<S> {
    /// On success, the result contains the encrypted connection and the
    /// longterm public key of the client.
    type Item = Result<(BoxDuplex<S>, sign::PublicKey), (ServerHandshakeFailure, S)>;
    type Error = (io::Error, S);

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let (res, stream) = try_ready!(self.0.poll());
        match res {
            Ok(outcome) => {
                Ok(Async::Ready(Ok((BoxDuplex::new(stream,
                                                   outcome.encryption_key(),
                                                   outcome.decryption_key(),
                                                   outcome.encryption_nonce(),
                                                   outcome.decryption_nonce()),
                                    outcome.peer_longterm_pk()))))
            }
            Err(failure) => Ok(Async::Ready(Err((failure, stream)))),
        }
    }
}

/// A future that accepts a secret-handshake based on a filter function and then
/// yields a channel that encrypts/decrypts all data via box-stream.
pub struct ServerFilter<'a, S, FilterFn, AsyncBool>(ServerHandshakerWithFilter<'a,
                                                                                S,
                                                                                FilterFn,
                                                                                AsyncBool>);

impl<'a, S, FilterFn, AsyncBool> ServerFilter<'a, S, FilterFn, AsyncBool>
    where S: AsyncRead + AsyncWrite,
          FilterFn: FnOnce(&sign::PublicKey) -> AsyncBool,
          AsyncBool: Future<Item = bool>
{
    /// Create a new `Server` to accept a connection from a client which knows
    /// the server's public key, uses the right app key over the given `stream`
    /// and whose longterm public key is accepted by the filter function.
    ///
    /// Ephemeral keypairs can be generated via
    /// `sodiumoxide::crypto::box_::gen_keypair`.
    pub fn new(stream: S,
               filter_fn: FilterFn,
               network_identifier: &'a [u8; NETWORK_IDENTIFIER_BYTES],
               server_longterm_pk: &'a sign::PublicKey,
               server_longterm_sk: &'a sign::SecretKey,
               server_ephemeral_pk: &'a box_::PublicKey,
               server_ephemeral_sk: &'a box_::SecretKey)
               -> ServerFilter<'a, S, FilterFn, AsyncBool> {
        ServerFilter(ServerHandshakerWithFilter::new(stream,
                                                     filter_fn,
                                                     network_identifier,
                                                     server_longterm_pk,
                                                     server_longterm_sk,
                                                     &server_ephemeral_pk,
                                                     &server_ephemeral_sk))
    }
}

impl<'a, S, FilterFn, AsyncBool> Future for ServerFilter<'a, S, FilterFn, AsyncBool>
    where S: AsyncRead + AsyncWrite,
          FilterFn: FnOnce(&sign::PublicKey) -> AsyncBool,
          AsyncBool: Future<Item = bool>
{
    /// On success, the result contains the encrypted connection and the
    /// longterm public key of the client.
    type Item = Result<(BoxDuplex<S>, sign::PublicKey), (ServerHandshakeFailureWithFilter, S)>;
    type Error = (ServerHandshakeError<AsyncBool::Error>, S);

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let (res, stream) = try_ready!(self.0.poll());
        match res {
            Ok(outcome) => {
                Ok(Async::Ready(Ok((BoxDuplex::new(stream,
                                                   outcome.encryption_key(),
                                                   outcome.decryption_key(),
                                                   outcome.encryption_nonce(),
                                                   outcome.decryption_nonce()),
                                    outcome.peer_longterm_pk()))))
            }
            Err(failure) => Ok(Async::Ready(Err((failure, stream)))),
        }
    }
}

/// A future that accepts a secret-handshake based on a filter function and then
/// yields a channel that encrypts/decrypts all data via box-stream.
///
/// This copies the handshake keys so that it is not constrained by the key's lifetime.
pub struct OwningServerFilter<S, FilterFn, AsyncBool>(OwningServerHandshakerWithFilter<S,
                                                                                FilterFn,
                                                                                AsyncBool>);

impl<S, FilterFn, AsyncBool> OwningServerFilter<S, FilterFn, AsyncBool>
    where S: AsyncRead + AsyncWrite,
          FilterFn: FnOnce(&sign::PublicKey) -> AsyncBool,
          AsyncBool: Future<Item = bool>
{
    /// Create a new `Server` to accept a connection from a client which knows
    /// the server's public key, uses the right app key over the given `stream`
    /// and whose longterm public key is accepted by the filter function.
    ///
    /// This copies the handshake keys so that it is not constrained by the key's lifetime.
    ///
    /// Ephemeral keypairs can be generated via
    /// `sodiumoxide::crypto::box_::gen_keypair`.
    pub fn new(stream: S,
               filter_fn: FilterFn,
               network_identifier: &[u8; NETWORK_IDENTIFIER_BYTES],
               server_longterm_pk: &sign::PublicKey,
               server_longterm_sk: &sign::SecretKey,
               server_ephemeral_pk: &box_::PublicKey,
               server_ephemeral_sk: &box_::SecretKey)
               -> OwningServerFilter<S, FilterFn, AsyncBool> {
        OwningServerFilter(OwningServerHandshakerWithFilter::new(stream,
                                                                 filter_fn,
                                                                 network_identifier,
                                                                 server_longterm_pk,
                                                                 server_longterm_sk,
                                                                 &server_ephemeral_pk,
                                                                 &server_ephemeral_sk))
    }
}

impl<S, FilterFn, AsyncBool> Future for OwningServerFilter<S, FilterFn, AsyncBool>
    where S: AsyncRead + AsyncWrite,
          FilterFn: FnOnce(&sign::PublicKey) -> AsyncBool,
          AsyncBool: Future<Item = bool>
{
    /// On success, the result contains the encrypted connection and the
    /// longterm public key of the client.
    type Item = Result<(BoxDuplex<S>, sign::PublicKey), (ServerHandshakeFailureWithFilter, S)>;
    type Error = (ServerHandshakeError<AsyncBool::Error>, S);

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let (res, stream) = try_ready!(self.0.poll());
        match res {
            Ok(outcome) => {
                Ok(Async::Ready(Ok((BoxDuplex::new(stream,
                                                   outcome.encryption_key(),
                                                   outcome.decryption_key(),
                                                   outcome.encryption_nonce(),
                                                   outcome.decryption_nonce()),
                                    outcome.peer_longterm_pk()))))
            }
            Err(failure) => Ok(Async::Ready(Err((failure, stream)))),
        }
    }
}