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
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.

// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Parity Ethereum.  If not, see <http://www.gnu.org/licenses/>.

// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

use crate::{
    connection::Connection,
    keylib::{crypto::ecies, Secret},
    node_table::NodeId,
    service::HostMetadata,
    Error,
};
use cfx_types::{Public, H256};
use io::{IoContext, StreamToken};
use log::{debug, error, trace};
use mio::tcp::TcpStream;
use priority_send_queue::SendQueuePriority;
use std::{
    sync::atomic::{AtomicBool, Ordering},
    time::Duration,
};

const AUTH_PACKET_SIZE: usize = 209;
const ACK_OF_AUTH_PACKET_SIZE: usize = 177;
const ACK_OF_ACK_PACKET_SIZE: usize = 145;
const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);

// used for test purpose only to bypass the cryptography
pub static BYPASS_CRYPTOGRAPHY: AtomicBool = AtomicBool::new(false);

#[derive(PartialEq, Eq, Debug)]
pub enum HandshakeState {
    /// Just created
    New,
    /// Waiting for auth packet
    ReadingAuth,
    /// Waiting for ack of auth packet
    ReadingAckofAuth,
    /// Waiting for ack of ack packet
    ReadingAckofAck,
    /// Ready to start a session
    StartSession,
}

/// Three-way handshake to exchange the node Id.
pub struct Handshake {
    /// Remote node public key
    pub id: NodeId,
    /// Underlying connection
    pub connection: Connection,
    /// Handshake state
    pub state: HandshakeState,
    /// nonce for verification
    nonce: H256,
}

impl Handshake {
    /// Create a new handshake object
    pub fn new(
        token: StreamToken, id: Option<&NodeId>, socket: TcpStream,
    ) -> Self {
        Handshake {
            id: id.cloned().unwrap_or_else(NodeId::default),
            connection: Connection::new(token, socket),
            state: HandshakeState::New,
            nonce: H256::random(),
        }
    }

    /// Start a handshake
    pub fn start<Message>(
        &mut self, io: &IoContext<Message>, host: &HostMetadata,
    ) -> Result<(), Error>
    where Message: Send + Clone + Sync + 'static {
        io.register_timer(self.connection.token(), HANDSHAKE_TIMEOUT)?;

        if !self.id.is_zero() {
            self.write_auth(io, host.id())?;
        } else {
            self.state = HandshakeState::ReadingAuth;
        };

        Ok(())
    }

    /// Check if handshake is complete
    pub fn done(&self) -> bool { self.state == HandshakeState::StartSession }

    /// Readable IO handler. Drives the state change.
    pub fn readable<Message>(
        &mut self, io: &IoContext<Message>, host: &HostMetadata,
    ) -> Result<bool, Error>
    where Message: Send + Clone + Sync + 'static {
        trace!("handshake readable enter, state = {:?}", self.state);

        let data = match self.connection.readable()? {
            Some(data) => data,
            None => return Ok(false),
        };

        match self.state {
            HandshakeState::New => {
                error!("handshake readable invalid for New state");
            }
            HandshakeState::StartSession => {
                error!("handshake readable invalid for StartSession state");
            }
            HandshakeState::ReadingAuth => {
                if data.len() == 64
                    && BYPASS_CRYPTOGRAPHY.load(Ordering::Relaxed)
                {
                    self.read_node_id(io, host.id(), &data)?;
                } else {
                    self.read_auth(io, host.secret(), &data)?;
                }
            }
            HandshakeState::ReadingAckofAuth => {
                self.read_ack_of_auth(io, host.secret(), &data)?;
            }
            HandshakeState::ReadingAckofAck => {
                self.read_ack_of_ack(host.secret(), &data)?;
            }
        }

        if self.state == HandshakeState::StartSession {
            io.clear_timer(self.connection.token())?;
        }

        trace!("handshake readable leave, state = {:?}", self.state);

        Ok(true)
    }

    /// Sends auth message
    fn write_auth<Message>(
        &mut self, io: &IoContext<Message>, public: &Public,
    ) -> Result<(), Error>
    where Message: Send + Clone + Sync + 'static {
        trace!(
            "Sending handshake auth to {:?}",
            self.connection.remote_addr_str()
        );

        let mut data =
            Vec::with_capacity(Public::len_bytes() + H256::len_bytes());
        data.extend_from_slice(public.as_bytes());
        data.extend_from_slice(self.nonce.as_bytes());

        let message = ecies::encrypt(&self.id, &[], &data)?;

        self.connection.send(io, message, SendQueuePriority::High)?;
        self.state = HandshakeState::ReadingAckofAuth;

        Ok(())
    }

    /// Parse, validate and confirm auth message
    fn read_auth<Message>(
        &mut self, io: &IoContext<Message>, secret: &Secret, data: &[u8],
    ) -> Result<(), Error>
    where Message: Send + Clone + Sync + 'static {
        trace!(
            "Received handshake auth from {:?}",
            self.connection.remote_addr_str()
        );

        if data.len() != AUTH_PACKET_SIZE {
            debug!(
                "failed to read auth, wrong packet size {}, expected = {}",
                data.len(),
                AUTH_PACKET_SIZE
            );
            return Err(Error::BadProtocol.into());
        }

        let auth = ecies::decrypt(secret, &[], data)?;

        let (remote_public, remote_nonce) = auth.split_at(NodeId::len_bytes());
        self.id.assign_from_slice(remote_public);

        self.write_ack_of_auth(io, remote_nonce)
    }

    /// Sends ack of auth message
    fn write_ack_of_auth<Message>(
        &mut self, io: &IoContext<Message>, remote_nonce: &[u8],
    ) -> Result<(), Error>
    where Message: Send + Clone + Sync + 'static {
        trace!(
            "Sending handshake ack of auth to {:?}",
            self.connection.remote_addr_str()
        );

        let mut data =
            Vec::with_capacity(remote_nonce.len() + H256::len_bytes());
        data.extend_from_slice(remote_nonce);
        data.extend_from_slice(self.nonce.as_ref());

        let message = ecies::encrypt(&self.id, &[], &data)?;

        self.connection.send(io, message, SendQueuePriority::High)?;
        self.state = HandshakeState::ReadingAckofAck;

        Ok(())
    }

    // for test purpose only
    fn read_node_id<Message>(
        &mut self, io: &IoContext<Message>, public: &Public, data: &[u8],
    ) -> Result<(), Error>
    where Message: Send + Clone + Sync + 'static {
        trace!(
            "Received handshake auth from {:?}, node id len = {}",
            self.connection.remote_addr_str(),
            data.len()
        );
        assert_eq!(data.len(), 64);
        self.id.assign_from_slice(data);
        self.connection.send(
            io,
            public.as_bytes().into(),
            SendQueuePriority::High,
        )?;
        self.state = HandshakeState::StartSession;
        Ok(())
    }

    /// Parse and validate ack of auth message
    fn read_ack_of_auth<Message>(
        &mut self, io: &IoContext<Message>, secret: &Secret, data: &[u8],
    ) -> Result<(), Error>
    where Message: Send + Clone + Sync + 'static {
        trace!(
            "Received handshake ack of auth from {:?}",
            self.connection.remote_addr_str()
        );

        if data.len() != ACK_OF_AUTH_PACKET_SIZE {
            debug!(
                "failed to read ack of auth, wrong packet size {}, expected = {}",
                data.len(),
                ACK_OF_AUTH_PACKET_SIZE
            );
            return Err(Error::BadProtocol.into());
        }

        let ack = ecies::decrypt(secret, &[], data)?;

        let (self_nonce, remote_nonce) = ack.split_at(H256::len_bytes());

        if self_nonce != &self.nonce[..] {
            debug!("failed to read ack of auth, nonce mismatch");
            return Err(Error::BadProtocol.into());
        }

        self.write_ack_of_ack(io, remote_nonce)
    }

    fn write_ack_of_ack<Message>(
        &mut self, io: &IoContext<Message>, remote_nonce: &[u8],
    ) -> Result<(), Error>
    where Message: Send + Clone + Sync + 'static {
        trace!(
            "Sending handshake ack of ack to {:?}",
            self.connection.remote_addr_str()
        );

        let message = ecies::encrypt(&self.id, &[], remote_nonce)?;

        self.connection.send(io, message, SendQueuePriority::High)?;
        self.state = HandshakeState::StartSession;

        Ok(())
    }

    fn read_ack_of_ack(
        &mut self, secret: &Secret, data: &[u8],
    ) -> Result<(), Error> {
        trace!(
            "Received handshake ack of ack from {:?}",
            self.connection.remote_addr_str()
        );

        if data.len() != ACK_OF_ACK_PACKET_SIZE {
            debug!(
                "failed to read ack of ack, wrong packet size {}, expected = {}",
                data.len(),
                ACK_OF_ACK_PACKET_SIZE
            );
            return Err(Error::BadProtocol.into());
        }

        let nonce = ecies::decrypt(secret, &[], data)?;

        if &nonce[..] != &self.nonce[..] {
            debug!("failed to read ack of ack, nonce mismatch");
            return Err(Error::BadProtocol.into());
        }

        self.state = HandshakeState::StartSession;

        Ok(())
    }
}