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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
// Copyright 2019 Parity Technologies (UK) Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

//! Noise protocol handshake I/O.

mod payload;

use crate::error::NoiseError;
use crate::protocol::{Protocol, PublicKey, KeypairIdentity};
use libp2p_core::identity;
use futures::{future, Async, Future, future::FutureResult, Poll};
use std::{mem, io};
use tokio_io::{io as nio, AsyncWrite, AsyncRead};
use protobuf::Message;

use super::NoiseOutput;

/// A future performing a Noise handshake pattern.
pub struct Handshake<T, C>(
    Box<dyn Future<
        Item = <Handshake<T, C> as Future>::Item,
        Error = <Handshake<T, C> as Future>::Error
    > + Send>
);

impl<T, C> Future for Handshake<T, C> {
    type Error = NoiseError;
    type Item = (RemoteIdentity<C>, NoiseOutput<T>);

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        self.0.poll()
    }
}

/// The identity of the remote established during a handshake.
pub enum RemoteIdentity<C> {
    /// The remote provided no identifying information.
    ///
    /// The identity of the remote is unknown and must be obtained through
    /// a different, out-of-band channel.
    Unknown,

    /// The remote provided a static DH public key.
    ///
    /// The static DH public key is authentic in the sense that a successful
    /// handshake implies that the remote possesses a corresponding secret key.
    ///
    /// > **Note**: To rule out active attacks like a MITM, trust in the public key must
    /// > still be established, e.g. by comparing the key against an expected or
    /// > otherwise known public key.
    StaticDhKey(PublicKey<C>),

    /// The remote provided a public identity key in addition to a static DH
    /// public key and the latter is authentic w.r.t. the former.
    ///
    /// > **Note**: To rule out active attacks like a MITM, trust in the public key must
    /// > still be established, e.g. by comparing the key against an expected or
    /// > otherwise known public key.
    IdentityKey(identity::PublicKey)
}

/// The options for identity exchange in an authenticated handshake.
///
/// > **Note**: Even if a remote's public identity key is known a priori,
/// > unless the authenticity of the key is [linked](Protocol::linked) to
/// > the authenticity of a remote's static DH public key, an authenticated
/// > handshake will still send the associated signature of the provided
/// > local [`KeypairIdentity`] in order for the remote to verify that the static
/// > DH public key is authentic w.r.t. the known public identity key.
pub enum IdentityExchange {
    /// Send the local public identity to the remote.
    ///
    /// The remote identity is unknown (i.e. expected to be received).
    Mutual,
    /// Send the local public identity to the remote.
    ///
    /// The remote identity is known.
    Send { remote: identity::PublicKey },
    /// Don't send the local public identity to the remote.
    ///
    /// The remote identity is unknown, i.e. expected to be received.
    Receive,
    /// Don't send the local public identity to the remote.
    ///
    /// The remote identity is known, thus identities must be mutually known
    /// in order for the handshake to succeed.
    None { remote: identity::PublicKey }
}

impl<T, C> Handshake<T, C>
where
    T: AsyncRead + AsyncWrite + Send + 'static,
    C: Protocol<C> + AsRef<[u8]> + Send + 'static,
{
    /// Creates an authenticated Noise handshake for the initiator of a
    /// single roundtrip (2 message) handshake pattern.
    ///
    /// Subject to the chosen [`IdentityExchange`], this message sequence
    /// identifies the local node to the remote with the first message payload
    /// (i.e. unencrypted) and expects the remote to identify itself in the
    /// second message payload.
    ///
    /// This message sequence is suitable for authenticated 2-message Noise handshake
    /// patterns where the static keys of the initiator and responder are either
    /// known (i.e. appear in the pre-message pattern) or are sent with
    /// the first and second message, respectively (e.g. `IK` or `IX`).
    ///
    /// ```raw
    /// initiator -{id}-> responder
    /// initiator <-{id}- responder
    /// ```
    pub fn rt1_initiator(
        io: T,
        session: Result<snow::Session, NoiseError>,
        identity: KeypairIdentity,
        identity_x: IdentityExchange
    ) -> Handshake<T, C> {
        Handshake(Box::new(
            State::new(io, session, identity, identity_x)
                .and_then(State::send_identity)
                .and_then(State::recv_identity)
                .and_then(State::finish)))
    }

    /// Creates an authenticated Noise handshake for the responder of a
    /// single roundtrip (2 message) handshake pattern.
    ///
    /// Subject to the chosen [`IdentityExchange`], this message sequence expects the
    /// remote to identify itself in the first message payload (i.e. unencrypted)
    /// and identifies the local node to the remote in the second message payload.
    ///
    /// This message sequence is suitable for authenticated 2-message Noise handshake
    /// patterns where the static keys of the initiator and responder are either
    /// known (i.e. appear in the pre-message pattern) or are sent with the first
    /// and second message, respectively (e.g. `IK` or `IX`).
    ///
    /// ```raw
    /// initiator -{id}-> responder
    /// initiator <-{id}- responder
    /// ```
    pub fn rt1_responder(
        io: T,
        session: Result<snow::Session, NoiseError>,
        identity: KeypairIdentity,
        identity_x: IdentityExchange,
    ) -> Handshake<T, C> {
        Handshake(Box::new(
            State::new(io, session, identity, identity_x)
                .and_then(State::recv_identity)
                .and_then(State::send_identity)
                .and_then(State::finish)))
    }

    /// Creates an authenticated Noise handshake for the initiator of a
    /// 1.5-roundtrip (3 message) handshake pattern.
    ///
    /// Subject to the chosen [`IdentityExchange`], this message sequence expects
    /// the remote to identify itself in the second message payload and
    /// identifies the local node to the remote in the third message payload.
    /// The first (unencrypted) message payload is always empty.
    ///
    /// This message sequence is suitable for authenticated 3-message Noise handshake
    /// patterns where the static keys of the responder and initiator are either known
    /// (i.e. appear in the pre-message pattern) or are sent with the second and third
    /// message, respectively (e.g. `XX`).
    ///
    /// ```raw
    /// initiator --{}--> responder
    /// initiator <-{id}- responder
    /// initiator -{id}-> responder
    /// ```
    pub fn rt15_initiator(
        io: T,
        session: Result<snow::Session, NoiseError>,
        identity: KeypairIdentity,
        identity_x: IdentityExchange
    ) -> Handshake<T, C> {
        Handshake(Box::new(
            State::new(io, session, identity, identity_x)
                .and_then(State::send_empty)
                .and_then(State::recv_identity)
                .and_then(State::send_identity)
                .and_then(State::finish)))
    }

    /// Creates an authenticated Noise handshake for the responder of a
    /// 1.5-roundtrip (3 message) handshake pattern.
    ///
    /// Subject to the chosen [`IdentityExchange`], this message sequence
    /// identifies the local node in the second message payload and expects
    /// the remote to identify itself in the third message payload. The first
    /// (unencrypted) message payload is always empty.
    ///
    /// This message sequence is suitable for authenticated 3-message Noise handshake
    /// patterns where the static keys of the responder and initiator are either known
    /// (i.e. appear in the pre-message pattern) or are sent with the second and third
    /// message, respectively (e.g. `XX`).
    ///
    /// ```raw
    /// initiator --{}--> responder
    /// initiator <-{id}- responder
    /// initiator -{id}-> responder
    /// ```
    pub fn rt15_responder(
        io: T,
        session: Result<snow::Session, NoiseError>,
        identity: KeypairIdentity,
        identity_x: IdentityExchange
    ) -> Handshake<T, C> {
        Handshake(Box::new(
            State::new(io, session, identity, identity_x)
                .and_then(State::recv_empty)
                .and_then(State::send_identity)
                .and_then(State::recv_identity)
                .and_then(State::finish)))
    }
}

//////////////////////////////////////////////////////////////////////////////
// Internal

/// Handshake state.
struct State<T> {
    /// The underlying I/O resource.
    io: NoiseOutput<T>,
    /// The associated public identity of the local node's static DH keypair,
    /// which can be sent to the remote as part of an authenticated handshake.
    identity: KeypairIdentity,
    /// The received signature over the remote's static DH public key, if any.
    dh_remote_pubkey_sig: Option<Vec<u8>>,
    /// The known or received public identity key of the remote, if any.
    id_remote_pubkey: Option<identity::PublicKey>,
    /// Whether to send the public identity key of the local node to the remote.
    send_identity: bool,
}

impl<T: io::Read> io::Read for State<T> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.io.read(buf)
    }
}

impl<T: io::Write> io::Write for State<T> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        self.io.write(buf)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.io.flush()
    }
}

impl<T: AsyncRead> AsyncRead for State<T> {
    unsafe fn prepare_uninitialized_buffer(&self, buf: &mut [u8]) -> bool {
        self.io.prepare_uninitialized_buffer(buf)
    }
    fn read_buf<B: bytes::BufMut>(&mut self, buf: &mut B) -> Poll<usize, io::Error> {
        self.io.read_buf(buf)
    }
}

impl<T: AsyncWrite> AsyncWrite for State<T> {
    fn shutdown(&mut self) -> Poll<(), io::Error> {
        self.io.shutdown()
    }
}

impl<T> State<T> {
    /// Initializes the state for a new Noise handshake, using the given local
    /// identity keypair and local DH static public key. The handshake messages
    /// will be sent and received on the given I/O resource and using the
    /// provided session for cryptographic operations according to the chosen
    /// Noise handshake pattern.
    fn new(
        io: T,
        session: Result<snow::Session, NoiseError>,
        identity: KeypairIdentity,
        identity_x: IdentityExchange
    ) -> FutureResult<Self, NoiseError> {
        let (id_remote_pubkey, send_identity) = match identity_x {
            IdentityExchange::Mutual => (None, true),
            IdentityExchange::Send { remote } => (Some(remote), true),
            IdentityExchange::Receive => (None, false),
            IdentityExchange::None { remote } => (Some(remote), false)
        };
        future::result(session.map(|s|
            State {
                identity,
                io: NoiseOutput::new(io, s),
                dh_remote_pubkey_sig: None,
                id_remote_pubkey,
                send_identity
            }
        ))
    }
}

impl<T> State<T>
{
    /// Finish a handshake, yielding the established remote identity and the
    /// [`NoiseOutput`] for communicating on the encrypted channel.
    fn finish<C>(self) -> FutureResult<(RemoteIdentity<C>, NoiseOutput<T>), NoiseError>
    where
        C: Protocol<C> + AsRef<[u8]>
    {
        let dh_remote_pubkey = match self.io.session.get_remote_static() {
            None => None,
            Some(k) => match C::public_from_bytes(k) {
                Err(e) => return future::err(e),
                Ok(dh_pk) => Some(dh_pk)
            }
        };
        match self.io.session.into_transport_mode() {
            Err(e) => future::err(e.into()),
            Ok(s) => {
                let remote = match (self.id_remote_pubkey, dh_remote_pubkey) {
                    (_, None) => RemoteIdentity::Unknown,
                    (None, Some(dh_pk)) => RemoteIdentity::StaticDhKey(dh_pk),
                    (Some(id_pk), Some(dh_pk)) => {
                        if C::verify(&id_pk, &dh_pk, &self.dh_remote_pubkey_sig) {
                            RemoteIdentity::IdentityKey(id_pk)
                        } else {
                            return future::err(NoiseError::InvalidKey)
                        }
                    }
                };
                future::ok((remote, NoiseOutput { session: s, .. self.io }))
            }
        }
    }
}

impl<T> State<T> {
    /// Creates a future that sends a Noise handshake message with an empty payload.
    fn send_empty(self) -> SendEmpty<T> {
        SendEmpty { state: SendState::Write(self) }
    }

    /// Creates a future that expects to receive a Noise handshake message with an empty payload.
    fn recv_empty(self) -> RecvEmpty<T> {
        RecvEmpty { state: RecvState::Read(self) }
    }

    /// Creates a future that sends a Noise handshake message with a payload identifying
    /// the local node to the remote.
    fn send_identity(self) -> SendIdentity<T> {
        SendIdentity { state: SendIdentityState::Init(self) }
    }

    /// Creates a future that expects to receive a Noise handshake message with a
    /// payload identifying the remote.
    fn recv_identity(self) -> RecvIdentity<T> {
        RecvIdentity { state: RecvIdentityState::Init(self) }
    }
}

//////////////////////////////////////////////////////////////////////////////
// Handshake Message Futures

// RecvEmpty -----------------------------------------------------------------

/// A future for receiving a Noise handshake message with an empty payload.
///
/// Obtained from [`Handshake::recv_empty`].
struct RecvEmpty<T> {
    state: RecvState<T>
}

enum RecvState<T> {
    Read(State<T>),
    Done
}

impl<T> Future for RecvEmpty<T>
where
    T: AsyncRead
{
    type Error = NoiseError;
    type Item = State<T>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match mem::replace(&mut self.state, RecvState::Done) {
            RecvState::Read(mut st) =>  {
                if !st.io.poll_read(&mut [])?.is_ready() {
                    self.state = RecvState::Read(st);
                    return Ok(Async::NotReady)
                }
                Ok(Async::Ready(st))
            },
            RecvState::Done => panic!("RecvEmpty polled after completion")
        }
    }
}

// SendEmpty -----------------------------------------------------------------

/// A future for sending a Noise handshake message with an empty payload.
///
/// Obtained from [`Handshake::send_empty`].
struct SendEmpty<T> {
    state: SendState<T>
}

enum SendState<T> {
    Write(State<T>),
    Flush(State<T>),
    Done
}

impl<T> Future for SendEmpty<T>
where
    T: AsyncWrite
{
    type Error = NoiseError;
    type Item = State<T>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            match mem::replace(&mut self.state, SendState::Done) {
                SendState::Write(mut st) => {
                    if !st.io.poll_write(&mut [])?.is_ready() {
                        self.state = SendState::Write(st);
                        return Ok(Async::NotReady)
                    }
                    self.state = SendState::Flush(st);
                },
                SendState::Flush(mut st) => {
                    if !st.io.poll_flush()?.is_ready() {
                        self.state = SendState::Flush(st);
                        return Ok(Async::NotReady)
                    }
                    return Ok(Async::Ready(st))
                }
                SendState::Done => panic!("SendEmpty polled after completion")
            }
        }
    }
}

// RecvIdentity --------------------------------------------------------------

/// A future for receiving a Noise handshake message with a payload
/// identifying the remote.
///
/// Obtained from [`Handshake::recv_identity`].
struct RecvIdentity<T> {
    state: RecvIdentityState<T>
}

enum RecvIdentityState<T> {
    Init(State<T>),
    ReadPayloadLen(nio::ReadExact<State<T>, [u8; 2]>),
    ReadPayload(nio::ReadExact<State<T>, Vec<u8>>),
    Done
}

impl<T> Future for RecvIdentity<T>
where
    T: AsyncRead,
{
    type Error = NoiseError;
    type Item = State<T>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            match mem::replace(&mut self.state, RecvIdentityState::Done) {
                RecvIdentityState::Init(st) => {
                    self.state = RecvIdentityState::ReadPayloadLen(nio::read_exact(st, [0, 0]));
                },
                RecvIdentityState::ReadPayloadLen(mut read_len) => {
                    if let Async::Ready((st, bytes)) = read_len.poll()? {
                        let len = u16::from_be_bytes(bytes) as usize;
                        let buf = vec![0; len];
                        self.state = RecvIdentityState::ReadPayload(nio::read_exact(st, buf));
                    } else {
                        self.state = RecvIdentityState::ReadPayloadLen(read_len);
                        return Ok(Async::NotReady);
                    }
                },
                RecvIdentityState::ReadPayload(mut read_payload) => {
                    if let Async::Ready((mut st, bytes)) = read_payload.poll()? {
                        let pb: payload::Identity = protobuf::parse_from_bytes(&bytes)?;
                        if !pb.pubkey.is_empty() {
                            let pk = identity::PublicKey::from_protobuf_encoding(pb.get_pubkey())
                                .map_err(|_| NoiseError::InvalidKey)?;
                            if let Some(ref k) = st.id_remote_pubkey {
                                if k != &pk {
                                    return Err(NoiseError::InvalidKey)
                                }
                            }
                            st.id_remote_pubkey = Some(pk);
                        }
                        if !pb.signature.is_empty() {
                            st.dh_remote_pubkey_sig = Some(pb.signature)
                        }
                        return Ok(Async::Ready(st))
                    } else {
                        self.state = RecvIdentityState::ReadPayload(read_payload);
                        return Ok(Async::NotReady)
                    }
                },
                RecvIdentityState::Done => panic!("RecvIdentity polled after completion")
            }
        }
    }
}

// SendIdentity --------------------------------------------------------------

/// A future for sending a Noise handshake message with a payload
/// identifying the local node to the remote.
///
/// Obtained from [`Handshake::send_identity`].
struct SendIdentity<T> {
    state: SendIdentityState<T>
}

enum SendIdentityState<T> {
    Init(State<T>),
    WritePayloadLen(nio::WriteAll<State<T>, [u8; 2]>, Vec<u8>),
    WritePayload(nio::WriteAll<State<T>, Vec<u8>>),
    Flush(State<T>),
    Done
}

impl<T> Future for SendIdentity<T>
where
    T: AsyncWrite,
{
    type Error = NoiseError;
    type Item = State<T>;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            match mem::replace(&mut self.state, SendIdentityState::Done) {
                SendIdentityState::Init(st) => {
                    let mut pb = payload::Identity::new();
                    if st.send_identity {
                        pb.set_pubkey(st.identity.public.clone().into_protobuf_encoding());
                    }
                    if let Some(ref sig) = st.identity.signature {
                        pb.set_signature(sig.clone());
                    }
                    let pb_bytes = pb.write_to_bytes()?;
                    let len = (pb_bytes.len() as u16).to_be_bytes();
                    let write_len = nio::write_all(st, len);
                    self.state = SendIdentityState::WritePayloadLen(write_len, pb_bytes);
                },
                SendIdentityState::WritePayloadLen(mut write_len, payload) => {
                    if let Async::Ready((st, _)) = write_len.poll()? {
                        self.state = SendIdentityState::WritePayload(nio::write_all(st, payload));
                    } else {
                        self.state = SendIdentityState::WritePayloadLen(write_len, payload);
                        return Ok(Async::NotReady)
                    }
                },
                SendIdentityState::WritePayload(mut write_payload) => {
                    if let Async::Ready((st, _)) = write_payload.poll()? {
                        self.state = SendIdentityState::Flush(st);
                    } else {
                        self.state = SendIdentityState::WritePayload(write_payload);
                        return Ok(Async::NotReady)
                    }
                },
                SendIdentityState::Flush(mut st) => {
                    if !st.poll_flush()?.is_ready() {
                        self.state = SendIdentityState::Flush(st);
                        return Ok(Async::NotReady)
                    }
                    return Ok(Async::Ready(st))
                },
                SendIdentityState::Done => panic!("SendIdentity polled after completion")
            }
        }
    }
}