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
//! Asynchronously accept handshakes.

use std::{error, io, fmt};
use std::error::Error;
use std::io::ErrorKind::{WriteZero, UnexpectedEof, Interrupted, WouldBlock};
use std::mem::uninitialized;

use sodiumoxide::crypto::{box_, sign};
use sodiumoxide::utils::memzero;
use futures::{Poll, Async, Future};
use futures::future::{ok, FutureResult};
use tokio_io::{AsyncRead, AsyncWrite};
use void::Void;

use crypto::*;

// TODO cleanup (warnings)

/// Performs the server side of a handshake.
pub struct ServerHandshaker<'a, S>(ServerHandshakerWithFilter<'a,
                                                               S,
                                                               fn(&sign::PublicKey)
                                                                  -> FutureResult<bool, Void>,
                                                               FutureResult<bool, Void>>);

impl<'a, S: AsyncRead + AsyncWrite> ServerHandshaker<'a, S> {
    /// Creates a new ServerHandshakerWithFilter to accept a connection from a
    /// client which knows the server's public key and uses the right app key
    /// over the given `stream`.
    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)
               -> ServerHandshaker<'a, S> {
        ServerHandshaker(ServerHandshakerWithFilter::new(stream,
                                                         const_async_true,
                                                         network_identifier,
                                                         &server_longterm_pk,
                                                         &server_longterm_sk,
                                                         &server_ephemeral_pk,
                                                         &server_ephemeral_sk))
    }
}

/// Future implementation to asynchronously drive a handshake.
impl<'a, S: AsyncRead + AsyncWrite> Future for ServerHandshaker<'a, S> {
    type Item = (Result<Outcome, ServerHandshakeFailure>, S);
    type Error = (io::Error, S);

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.0.poll() {
            Ok(Async::Ready((Ok(outcome), stream))) => Ok(Async::Ready((Ok(outcome), stream))),
            Ok(Async::Ready((Err(failure), stream))) => {
                match failure {
                    ServerHandshakeFailureWithFilter::InvalidMsg1 => {
                        Ok(Async::Ready((Err(ServerHandshakeFailure::InvalidMsg1), stream)))
                    }
                    ServerHandshakeFailureWithFilter::InvalidMsg3 => {
                        Ok(Async::Ready((Err(ServerHandshakeFailure::InvalidMsg3), stream)))
                    }
                    ServerHandshakeFailureWithFilter::UnauthorizedClient => unreachable!(),
                }
            }
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err((e, stream)) => {
                let new_err = match e {
                    ServerHandshakeError::FilterFnError(_) => unreachable!(),
                    ServerHandshakeError::IoError(io_err) => io_err,
                };

                Err((new_err, stream))
            }
        }
    }
}

fn const_async_true(_: &sign::PublicKey) -> FutureResult<bool, Void> {
    ok(true)
}

/// Reason why a server might reject the client although the handshake itself
/// was executed without IO errors.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum ServerHandshakeFailure {
    /// Received invalid msg1 from the client.
    InvalidMsg1,
    /// Received invalid msg3 from the client.
    InvalidMsg3,
}

/// Performs the server side of a handshake. Allows filtering clients based on
/// their longterm public key.
pub struct ServerHandshakerWithFilter<'a, S, FilterFn, AsyncBool> {
    stream: Option<S>,
    filter: Option<FilterStuff<FilterFn, AsyncBool>>,
    server: Server<'a>,
    state: State,
    data: [u8; MSG3_BYTES], // used to hold and cache the results of `server.create_server_challenge` and `server.create_server_ack`, and any data read from the client
    offset: usize, // offset into the data array at which to read/write
}

/// Zero buffered handshake data on dropping.
impl<'a, S, FilterFn, AsyncBool> Drop for ServerHandshakerWithFilter<'a, S, FilterFn, AsyncBool> {
    fn drop(&mut self) {
        memzero(&mut self.data);
    }
}

impl<'a, S, FilterFn, AsyncBool> ServerHandshakerWithFilter<'a, S, FilterFn, AsyncBool>
    where S: AsyncRead + AsyncWrite,
          FilterFn: FnOnce(&sign::PublicKey) -> AsyncBool,
          AsyncBool: Future<Item = bool>
{
    /// Creates a new ServerHandshakerWithFilter to accept a connection from a
    /// client which knows the server's public key and uses the right app key
    /// over the given `stream`.
    ///
    /// Once the client has revealed its longterm public key, `filter_fn` is
    /// invoked. If the returned `AsyncBool` resolves to `Ok(Async::Ready(false))`,
    /// the handshake is aborted.
    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)
               -> ServerHandshakerWithFilter<'a, S, FilterFn, AsyncBool> {
        ServerHandshakerWithFilter {
            stream: Some(stream),
            filter: Some(FilterFun(filter_fn)),
            server: Server::new(network_identifier,
                                &server_longterm_pk.0,
                                &server_longterm_sk.0,
                                &server_ephemeral_pk.0,
                                &server_ephemeral_sk.0),
            state: ReadMsg1,
            data: [0; MSG3_BYTES],
            offset: 0,
        }
    }
}

/// Future implementation to asynchronously drive a handshake.
impl<'a, S, FilterFn, AsyncBool> Future for ServerHandshakerWithFilter<'a, S, FilterFn, AsyncBool>
    where S: AsyncRead + AsyncWrite,
          FilterFn: FnOnce(&sign::PublicKey) -> AsyncBool,
          AsyncBool: Future<Item = bool>
{
    type Item = (Result<Outcome, ServerHandshakeFailureWithFilter>, S);
    type Error = (ServerHandshakeError<AsyncBool::Error>, S);

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let mut stream = self.stream
            .take()
            .expect("Polled ServerHandshaker after completion");

        match self.state {
            ReadMsg1 => {
                while self.offset < MSG1_BYTES {
                    match stream.read(&mut self.data[self.offset..MSG1_BYTES]) {
                        Ok(read) => {
                            if read == 0 {
                                return Err((io::Error::new(UnexpectedEof, "failed to read msg1")
                                                .into(),
                                            stream));
                            }
                            self.offset += read;
                        }
                        Err(ref e) if e.kind() == WouldBlock => {
                            self.stream = Some(stream);
                            return Ok(Async::NotReady);
                        }
                        Err(ref e) if e.kind() == Interrupted => {}
                        Err(e) => return Err((e.into(), stream)),
                    }
                }

                if !self.server
                        .verify_msg1(unsafe {
                                         &*(&self.data as *const [u8; MSG3_BYTES] as
                                            *const [u8; MSG1_BYTES])
                                     }) {
                    return Ok(Async::Ready((Err(ServerHandshakeFailureWithFilter::InvalidMsg1),
                                            stream)));
                }

                self.stream = Some(stream);
                self.offset = 0;
                self.state = WriteMsg2;
                self.server
                    .create_msg2(unsafe {
                                     &mut *(&mut self.data as *mut [u8; MSG3_BYTES] as
                                            *mut [u8; MSG2_BYTES])
                                 });
                return self.poll();
            }

            WriteMsg2 => {
                while self.offset < MSG2_BYTES {
                    match stream.write(&self.data[self.offset..MSG2_BYTES]) {
                        Ok(written) => {
                            if written == 0 {
                                return Err((io::Error::new(WriteZero, "failed to write msg2")
                                                .into(),
                                            stream));
                            }
                            self.offset += written;
                        }
                        Err(ref e) if e.kind() == WouldBlock => {
                            self.stream = Some(stream);
                            return Ok(Async::NotReady);
                        }
                        Err(ref e) if e.kind() == Interrupted => {}
                        Err(e) => return Err((e.into(), stream)),
                    }
                }

                self.stream = Some(stream);
                self.offset = 0;
                self.state = FlushMsg2;
                return self.poll();
            }

            FlushMsg2 => {
                match stream.flush() {
                    Ok(_) => {}
                    Err(ref e) if e.kind() == WouldBlock => {
                        self.stream = Some(stream);
                        return Ok(Async::NotReady);
                    }
                    Err(ref e) if e.kind() == Interrupted => {}
                    Err(e) => return Err((e.into(), stream)),
                }

                self.stream = Some(stream);
                self.state = ReadMsg3;
                return self.poll();
            }

            ReadMsg3 => {
                while self.offset < MSG3_BYTES {
                    match stream.read(&mut self.data[self.offset..MSG3_BYTES]) {
                        Ok(read) => {
                            if read == 0 {
                                return Err((io::Error::new(UnexpectedEof, "failed to read msg3")
                                                .into(),
                                            stream));
                            }
                            self.offset += read;
                        }
                        Err(ref e) if e.kind() == WouldBlock => {
                            self.stream = Some(stream);
                            return Ok(Async::NotReady);
                        }
                        Err(ref e) if e.kind() == Interrupted => {}
                        Err(e) => return Err((e.into(), stream)),
                    }
                }

                if !self.server.verify_msg3(&self.data) {
                    return Ok(Async::Ready((Err(ServerHandshakeFailureWithFilter::InvalidMsg3),
                                            stream)));
                }

                let filter_fn =
                    match self.filter
                              .take()
                              .expect("Attempted to poll ServerHandshaker after completion") {
                        FilterFun(f) => f,
                        FilterFuture(_) => unreachable!(),
                    };

                self.filter =
                    Some(FilterFuture(filter_fn(&sign::PublicKey(unsafe {
                                                 self.server.client_longterm_pub()
                                             }))));

                self.stream = Some(stream);
                self.offset = 0;
                self.state = FilterClient;
                return self.poll();
            }

            FilterClient => {
                let mut filter_future =
                    match self.filter
                              .take()
                              .expect("Attempted to poll ServerHandshaker after completion") {
                        FilterFun(_) => unreachable!(),
                        FilterFuture(f) => f,
                    };

                match filter_future.poll() {
                    Err(e) => return Err((ServerHandshakeError::FilterFnError(e), stream)),
                    Ok(Async::NotReady) => {
                        self.filter = Some(FilterFuture(filter_future));
                        self.stream = Some(stream);
                        return Ok(Async::NotReady);
                    }
                    Ok(Async::Ready(is_authorized)) => {
                        if !is_authorized {
                            return Ok(Async::Ready((Err(ServerHandshakeFailureWithFilter::UnauthorizedClient), stream)));
                        }

                        self.stream = Some(stream);
                        self.state = WriteMsg4;
                        self.server
                            .create_msg4(unsafe {
                                             &mut *(&mut self.data as *mut [u8; MSG3_BYTES] as
                                                    *mut [u8; MSG4_BYTES])
                                         });

                        return self.poll();
                    }
                }
            }

            WriteMsg4 => {
                while self.offset < MSG4_BYTES {
                    match stream.write(&self.data[self.offset..MSG4_BYTES]) {
                        Ok(written) => {
                            if written == 0 {
                                return Err((io::Error::new(WriteZero, "failed to write msg4")
                                                .into(),
                                            stream));
                            }
                            self.offset += written;
                        }
                        Err(ref e) if e.kind() == WouldBlock => {
                            self.stream = Some(stream);
                            return Ok(Async::NotReady);
                        }
                        Err(ref e) if e.kind() == Interrupted => {}
                        Err(e) => return Err((e.into(), stream)),
                    }
                }

                self.stream = Some(stream);
                self.offset = 0;
                self.state = FlushMsg4;
                return self.poll();
            }

            FlushMsg4 => {
                match stream.flush() {
                    Ok(_) => {}
                    Err(ref e) if e.kind() == WouldBlock => {
                        self.stream = Some(stream);
                        return Ok(Async::NotReady);
                    }
                    Err(ref e) if e.kind() == Interrupted => {}
                    Err(e) => return Err((e.into(), stream)),
                }

                let mut outcome = unsafe { uninitialized() };
                self.server.outcome(&mut outcome);
                return Ok(Async::Ready((Ok(outcome), stream)));
            }

        }
    }
}

/// A fatal error that occured during the execution of a handshake by a
/// filtering server.
#[derive(Debug)]
pub enum ServerHandshakeError<FilterErr> {
    /// An IO error occured during reading or writing. The contained error is
    /// guaranteed to not have kind `WouldBlock`.
    IoError(io::Error),
    /// The filter function errored, the error is wrapped in this variant.
    FilterFnError(FilterErr),
}

impl<FilterErr> From<io::Error> for ServerHandshakeError<FilterErr> {
    fn from(error: io::Error) -> Self {
        ServerHandshakeError::IoError(error)
    }
}

impl<FilterErr: error::Error> fmt::Display for ServerHandshakeError<FilterErr> {
    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
        try!(fmt.write_str(self.description()));
        if let Some(cause) = self.cause() {
            try!(write!(fmt, ": {}", cause));
        }
        Ok(())
    }
}

impl<FilterErr: error::Error> error::Error for ServerHandshakeError<FilterErr> {
    fn description(&self) -> &str {
        match *self {
            ServerHandshakeError::IoError(_) => "IO error during handshake",
            ServerHandshakeError::FilterFnError(_) => "Error during authentication",
        }
    }

    fn cause(&self) -> Option<&error::Error> {
        match *self {
            ServerHandshakeError::IoError(ref err) => Some(err),
            ServerHandshakeError::FilterFnError(ref err) => Some(err),
        }
    }
}

// State for the future state machine.
enum State {
    ReadMsg1,
    WriteMsg2,
    FlushMsg2,
    ReadMsg3,
    FilterClient,
    WriteMsg4,
    FlushMsg4,
}
use server::State::*;

enum FilterStuff<FilterFn, AsyncBool> {
    FilterFun(FilterFn),
    FilterFuture(AsyncBool),
}
use server::FilterStuff::*;

/// Reason why a filtering server might reject the client although the handshake itself
/// was executed without IO errors.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub enum ServerHandshakeFailureWithFilter {
    /// Received invalid msg1 from the client.
    InvalidMsg1,
    /// Received invalid msg3 from the client.
    InvalidMsg3,
    /// Filtered out the client based on its longterm public key.
    UnauthorizedClient,
}